Conditional Rendering

Conditional Renderingopen in new window is when we make the rendering of a React component dependent on the state of the application. This is accomplished by using an if statement or a conditional operator to create elements representing the current state.

if Statement

Consider these two components:

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

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

A third component, Greeting, can be created to determine which component to display depending on the user's logged-in status.

function Greeting (props) {
  const isLoggedIn = props.isLoggedIn

  if (isLoggedIn) {
    return <UserGreeting />
  }

  return <GuestGreeting />
}

root.render(<Greeting isLoggedIn={false} />)

Logical && operator

JavaScript expressions can be embedded into JSX by wrapping curly braces around them. When using the logical && operator, it is possible to conditionally include an element.

function List (props) {
  const items = props.items

  return (
    <div>
      {items.length > 0 &&
        <em>You have {items.length} items.</em>
      }
    </div>
  )
}

root.render(<List items={items} />)