Kodokon kodokon.com

Events and conditional rendering

React to user actions and show or hide elements based on conditions.

8 min · 3 questions

Open this lesson in Kodokon

An 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.

JSX
function AlertButton() {
  function handleClick() {
    alert("Button clicked!");
  }

  return (
    <button onClick={handleClick}>
      Click here
    </button>
  );
}
The handleClick function runs on every click

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...".

JSX
function Status({ isLoggedIn }) {
  return (
    <p>
      {isLoggedIn ? "Welcome!" : "Please sign in."}
    </p>
  );
}
Two possible messages depending on the value of isLoggedIn

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.

JSX
function Cart({ itemCount }) {
  return (
    <div>
      <h3>My cart</h3>
      {itemCount > 0 && <p>{itemCount} item(s)</p>}
    </div>
  );
}
The paragraph only appears if the cart is not empty

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which prop do you use to react to a click in React?
    • onclick
    • onClick
    • clickEvent
  2. Why write onClick={handleClick} without parentheses?
    • Because parentheses are forbidden in JSX
    • To make the page load faster
    • So the function runs on click, not on render
  3. What is displayed by {isVisible && <p>Info</p>} if isVisible is false?
    • Nothing at all
    • The Info paragraph is displayed anyway
    • React shows an error message