React to user actions and show or hide elements based on conditions.
Open this lesson in KodokonAn event is a user action: a click, a key press, a form submission... In React, you listen for an event by passing a function to a special prop: onClick for clicks, onChange for typing, and so on. Note the camelCase spelling: onClick with a capital C, not onclick as in HTML.
function AlertButton() {
function handleClick() {
alert("Button clicked!");
}
return (
<button onClick={handleClick}>
Click here
</button>
);
}The second tool in this lesson is conditional rendering, in other words showing different things depending on a condition. Like a shop sign that reads "Open" or "Closed", a component can choose what to display. The most common tool is the ternary operator: condition ? valueIfTrue : valueIfFalse, a compact way of writing "if... else...".
function Status({ isLoggedIn }) {
return (
<p>
{isLoggedIn ? "Welcome!" : "Please sign in."}
</p>
);
}And what about showing something or nothing at all? You use the && operator: in condition && element, the element is only displayed if the condition is true. If it is false, React simply renders nothing, with no error.
function Cart({ itemCount }) {
return (
<div>
<h3>My cart</h3>
{itemCount > 0 && <p>{itemCount} item(s)</p>}
</div>
);
}onClick={handleClick} without parentheses?{isVisible && <p>Info</p>} if isVisible is false?