Skip to content

React Conditional Rendering

Conditional rendering in React allows you to render different components or elements based on certain conditions. This enables you to control what content is displayed to the user based on the state of your application or specific conditions.

Here are a few common approaches to conditional rendering in React:

  1. If-Else Statements
  2. Ternary Operator
  3. && Operator

Using If-Else Statements

You can use regular JavaScript if-else statements within your render() method to conditionally render different components or elements. Here’s an example:

import React from 'react';

function MyComponent() {
  const isLoggedIn = true;

  if (isLoggedIn) {
    return <p>Welcome, User!</p>;
  } else {
    return <p>Please log in.</p>;
  }
}

export default MyComponent;

In this example, the isLoggedIn variable is used to determine whether to render the “Welcome, User!” message or the “Please log in.” message.

Ternary Operator

As mentioned earlier, you can use the ternary operator (condition ? expression1 : expression2) to perform conditional rendering. Here’s an example:

import React from 'react';

function MyComponent() {
  const isLoggedIn = true;

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

export default MyComponent;

In this example, the result of the ternary operator determines which component to render: <p>Welcome, User!</p> if isLoggedIn is true, or <p>Please log in.</p> if isLoggedIn is false.

&& Operator

The && operator can be used for simple conditions where you only need to render a component if a certain condition is met. Here’s an example:

import React from 'react';

function MyComponent() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn && <p>Welcome, User!</p>}
    </div>
  );
}

export default MyComponent;

In this example, the <p>Welcome, User!</p> component is only rendered if isLoggedIn is true. If isLoggedIn is false, nothing will be rendered.

These are just a few examples of conditional rendering in React. Depending on your specific use case and the complexity of your conditions, you may need to use other techniques such as switch statements or rendering components based on the state stored in your application’s state management system (e.g., Redux or React Context).

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments