Codepath

Conditional Rendering

Your App components will eventually need to display differently depending on a condition. In React, there is no special syntax for writing conditions. Instead, you rely on the same techniques use when writing JavaScript code.

As such, you will use standard JavaScript operators like if/else , the ? conditional operator or the logical && syntax to conditionally include JSX to represent the current state of the component that needs to be render

If/Else

let content;

if (isLoggedIn) {
  content = <DashboardPanel />;
} else {
  content = <LoginForm />;
}

return (
  <div>{content}</div>
);

Conditional Operator ?

Unlike if, this works inside JSX and can lead to more compact code

return (
  <div>
    {isLoggedIn ? (
      <DashboardPanel />
    ) : (
      <LoginForm />
    )}
  </div>
);

Logical AND Operator &&

Useful if there’s no need for the else branch.

return (
  <div>
    {isLoggedIn && <DashboardPanel />}
  </div>
);

Rendering nothing

If you need a given React component to render nothing, simply return null. This prevents the component from rendering.

function Banner(props) {
  if (!props.message) {
    return null;
  }

  return (
    <div>{props.message}</div>
  )
}
Fork me on GitHub