techStackGuru

React Conditional Rendering


React's conditional rendering allows you to display different content or components depending on the conditions.

We use the ternary operator (? :) to perform conditional rendering. It renders the expression after the ?: if the condition before it is true; otherwise, it renders the expression after the :.

Example

import React from 'react';

function App() {
  const isLoggedIn = false;

  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome, User!</h1>
      ) : (
        <h1>Welcome, Guest!</h1>
      )}
    </div>
  );
}

export default App; 

Here is an example of a simple React component named App. There is a boolean variable isLoggedIn inside this component that determines if the user is logged in.

We conditionally render different content based on the value of isLoggedIn. In the case of a valid isLoggedIn, we display a message such as "Welcome, User!" in the h1 tag. In the case of isLoggedIn being false, "Welcome, Guest!" is displayed.

Example 2

import React from 'react';

function UserProfile({ user }) {
  return (
    <div>
      {user ? (
        <div>
          <h2>{user.name}</h2>
          <p>Email: {user.email}</p>
          <p>Age: {user.age}</p>
        </div>
      ) : (
        <p>Loading user profile...</p>
      )}
    </div>
  );
}

export default UserProfile; 

This example has a component called UserProfile that takes a user object in its props. An object representing a user profile includes properties such as name, age, and email.

In the component, conditional rendering is performed based on whether a user object is true or false. Whenever a user object is truthy (i.e., it exists), the user profile, including name, email, and age, is rendered. Whenever a user object is false (e.g., null or undefined), a loading message appears.