Show List

Conditional rendering in React

Conditional rendering in React refers to the practice of only rendering certain parts of a component's UI based on certain conditions. This allows you to dynamically render different parts of your UI based on the state of your application.

Conditional rendering can be achieved in React using a combination of JavaScript constructs such as if statements and ternary operators, as well as using special React techniques such as the && operator and rendering components conditionally.

Here's an example of conditional rendering using a ternary operator in React:

const User = (props) => {
  return (
    <div>
      {props.isLoggedIn ? (
        <p>Welcome back!</p>
      ) : (
        <p>Please log in.</p>
      )}
    </div>
  );
};

ReactDOM.render(
  <User isLoggedIn={false} />,
  document.getElementById("root")
);

In this example, the User component uses a ternary operator to conditionally render different UI based on the value of the isLoggedIn prop. If isLoggedIn is true, the component will render "Welcome back!", otherwise it will render "Please log in."

Here's another example of conditional rendering using the && operator:

const Greeting = (props) => {
  return (
    <div>
      {props.isVisible && <p>Hello, {props.name}!</p>}
    </div>
  );
};

ReactDOM.render(
  <Greeting isVisible={false} name="John" />,
  document.getElementById("root")
);

In this example, the Greeting component uses the && operator to conditionally render the greeting message based on the value of the isVisible prop. If isVisible is true, the component will render the greeting message, otherwise it will not render anything.

To summarize, conditional rendering in React allows you to dynamically render different parts of your UI based on certain conditions. You can achieve this using a combination of JavaScript constructs and React techniques.


    Leave a Comment


  • captcha text