Conditional Rendering

It is the ability to render different user interface (UI) markup if a condition is true or false. In React, it allows us to render different elements or components based on a condition.

An example is where you want to show either login button or the logout button according to whether the user is already logged in or not.

You can use Ternary operator

import React, { useState } from "react";

function App() {
  const [ isLoggedIn, setIsLoggedIn ] = useState(false);
  return (
    <div>
      { isLoggedIn ? <button>Logout</button> : <button>Login</button> }
    </div>
  );
}

export default App;

You check if the value of the isLoggedIn state is true or false. If it is true this means the user has logged in, so you choose to show the logout button and vice versa.

In other cases you may want to either render a component or don't render anything. In such cases you can either use the previous ternary operator way, or the short circuit evaluation with logic &&.

{ isLoggedIn ? <Dashboard /> : null }

null here means not to display anything.

{ isLoggedIn && <Dashboard /> }

Only if the isLoggedIn is true the Dashboard component will be rendered.

Last updated