Conditional Rendering

Learn how you can render different components based on certain conditions.

Rendering components based on different conditions, conditional rendering for short, is a central concept in React. As React components are composed of JavaScript functions, objects, and classes under the hood, conditions behave like they would in regular JavaScript.

A React component renders a state of a user interface based on its props and its current state. In an ideal situation, this means that the component is free from side effects. To correctly deal with these different and changing parameters, using the render function to react to different conditions is a powerful feature. This allows us to render one view if our parameter is A, a different one if the parameter is B, or different options for displaying lists or blank data.

This is relatively simple, but you should still be aware of how to do conditional rendering in JSX. The render() function of class components, as well as functional components, can return:

  1. A React element (also in the form of JSX)
  2. A string
  3. A number
  4. null (if nothing should be rendered)
  5. An array of these types.

There are a few methods of keeping the render() method nice and clean which we will explain now.

if/else

Probably the most simple and commonly known way to conditionally render is using if/else:

const NotificationList = ({ items }) => {
  if (items.length) {
    return (
      <ul>
        {items.map((notification) => (
          <li>{notification.title}</li>
        ))}
      </ul>
    );
  }
  return <p>No new notifications</p>;
};

This is a relatively simple use case. The NotificationList component receives a list of items in the form of props. If the list contains any entries at all, they are rendered as a list item of an unordered list. If the list is empty, a message is returned informing the user that no new notifications are available.

Here is another more complex example. Let’s imagine we are working with a value that we want to make editable. Our component differentiates between the different modes of edit and view. Depending on which mode we are currently in, we either want to show the text (View mode) or see a text field containing the previously entered value (edit mode). Let’s see this example interactively.

Get hands-on with 1200+ tech skills courses.