Search

React Conditional Rendering

  • Share this:

There are several ways to perform conditional rendering in React. Here are some examples:

`if` statement

render() {
  let greeting;
  if (isLoggedIn) {
    greeting = <h1>Welcome back!</h1>;
  } else {
    greeting = <h1>Please log in</h1>;
  }
  return (
    <div>
      {greeting}
    </div>
  );
}

`Ternary` Operator

render() {
  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in</h1>}
    </div>
  );
}

`Switch` Statement

render() {
  let greeting;
  switch (userType) {
    case 'admin':
      greeting = <h1>Welcome back, admin!</h1>;
      break;
    case 'subscriber':
      greeting = <h1>Welcome back, subscriber!</h1>;
      break;
    default:
      greeting = <h1>Welcome back!</h1>;
      break;
  }
  return (
    <div>
      {greeting}
    </div>
  );
}

`&&` Operator

render() {
  return (
    <div>
      {isLoggedIn && <h1>Welcome back!</h1>}
    </div>
  );
}

`React.Fragment`

render() {
  return (
    <React.Fragment>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in</h1>}
      <p>Additional content goes here</p>
    </React.Fragment>
  );
}

`short-circuit evaluation`

render() {
  return isLoggedIn && (
    <div>
      <h1>Welcome back!</h1>
      <p>Additional content goes here</p>
    </div>
  );
}

Note that it is generally recommended to use the `&&` operator or a ternary operator for simple conditional rendering, and to use a `React.Fragment` or a `div` element for more complex conditional rendering.

Tags:

About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.