Conditional rendering

Conditional rendering in React allows you to render different components or elements based on certain conditions. Here are some common ways to achieve conditional rendering in React:

Using if statements


//MyComponent.jsx
function MyComponent(props) {
  if (props.isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign up.</h1>;
  }
}

Using the ternary operator


//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
   </div>
  );
}

Using logical && operator


//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn && <h1>Welcome back!</h1>}
      {!props.isLoggedIn && <h1>Please sign up.</h1>}
    </div>
  );
}

Conditional rendering with switch statement


//MyComponent.jsx
function MyComponent(props) {
  switch (props.status) {
    case 'loading':
      return <div>Loading...</div>;
    case 'error':
      return <div>Error!</div>;
    case 'success':
      return <div>Data loaded successfully!</div>;
    default:
      return null;
  }
}

Using Component with conditional rendering

You can create separate components for different conditions and use them conditionally.


//welcome.jsx
function Welcome() {
  return <h1>Welcome back!</h1>;
}

//SignUp.jsx
function SignUp() {
  return <h1>Please sign up.</h1>;
}

//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn ? <Welcome /> : <SignUp />}
    </div>
  );
}