Conditional Rendering in React

You can use React to construct different components that contain the behaviour you require. Afterward, depending on your application's state, you can only render some of them.

React's conditional rendering functions in the same way that JavaScript's conditions do. Create items that describe the current state using JavaScript operators like if or the conditional operator, and let React adapt the UI to match them.

Conditional if Rendering

Consider these two components:

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.!</h1>;
}

We’ll create a Greeting component that displays either of these components depending on whether a user is logged in:

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
// Try changing to isLoggedIn={true}:
root.render(<Greeting isLoggedIn={false} />);

This example renders a different greeting depending on the value of isLoggedIn prop.

Inline If with Logical && Operator

You may embed expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical && operator. It can be handy for conditionally including an element:

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h1>
          You have {unreadMessages.length} unread messages.
        </h1>
      }
    </div>
  );
}

const messages = ['React', 'Re: React', 'Re:Re: React'];

const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Mailbox unreadMessages={messages} />);

Briefly summarized:

  • if condition is a truthy value, <h2> is rendered
  • if condition is a falsy value, <h2> is not rendered

Note that returning a falsy expression will still cause the element after && to be skipped, but will return the falsy expression. In the example below, <div>0</div> will be returned by the render method.

render() {
  const count = 0;
  return (
    <div>
      {count && <h1>Messages: {count}</h1>}
    </div>
  );
}

Why is that? It’s nothing React specific, but rather a behaviour of JavaScript and other programming languages called short-circuit evaluation. I.e., if the first operand (condition) is falsy, the AND operator (&&) stops, and it does not evaluate the second operand (<h1>).

Why Not To Use “&&”

The short syntax of && is often preferred, and it works. But! Just because you can don’t mean you should.

In our case from above, if the condition evaluates to true or false, you get what you’d expect — <h1> is or is not rendered respectively. All good so far. However, if the condition doesn’t evaluate to a boolean, it may cause trouble.

For example:

  • if condition is 0, 0 is displayed in the UI
  • if condition is undefined, you’ll get an error: "Uncaught Error: Error(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."

What To Use Instead Of “&&”

To avoid showing something you don’t want in the UI, such as 0, that could mess up the layout, use the JavaScript ternary operator instead. I.e.,

count ? <h1>Messages: {count} <h1/> : null;

To prevent avoidable UI bugs, use the JavaScript ternary operator for conditional rendering of React components instead of the logical AND operator. It’s a simple spell, but quite unbreakable.

I hope most of you find the strategy discussed here to be useful. Thank you for reading, and feel free to ask any questions in the comments section below.

Post a Comment

0 Comments