RSRobince Studio

Conditional Rendering

Components often need to show different output depending on a value. React uses plain JavaScript for this, so there is no special syntax to learn.

Use && to render something only when a condition is true, and the ternary operator to choose between two outputs.

  • condition && element renders the element only when condition is truthy
  • condition ? a : b picks a when true, otherwise b
  • Return null to render nothing at all
function Greeting({ loggedIn }) {
  return loggedIn ? <p>Welcome back</p> : <p>Please sign in</p>;
}
Keep conditions simple inside JSX. If logic grows, compute a variable above the return.
Try it yourself

Loading editor…