Conditional Rendering and Loops in React

Rendering conditions and loops in React are done using conditional statements and loop structures in JSX.

 

1. Rendering conditions

- Using if-else: You can use the if-else structure in JSX to check a condition and render different elements based on that condition.

For example:

function List({ list }) {
  if (!list) {
    return null;
  }

  if (!list.length) {
    return <p>Sorry.</p>;
  } else {
    return (
      <div>
        {list.map(item => <ListItem item={item} />)}
      </div>
    );
  }
}

- Using the ternary operator: You can also use the ternary operator to shorten the if-else structure in JSX.

For example:

 {isLoggedin ? <WelcomeUser /> : <Login />}

- Using the logical && operator: When you only want to display an element if a condition is true, you can use the logical && operator.

For example:

{isLoggedIn && <WelcomeUser />}

 

2. Rendering loops

- Using map: You can use the map method to iterate over an array and render corresponding elements in JSX.

For example

 {users.map((user) => (
       <li key={user.id}>{user.name}</li>
 ))}

- Using a for loop: You can also use a for loop to iterate over an array and render corresponding elements in JSX.

For example:

let usersList = [];
for (let i = 0; i < users.length; i++) {
  usersList.push(<li key={users[i].id}>{users[i].name}</li>);
}
return <ul>{usersList}</ul>;

- Using forEach: You can also use the forEach method to iterate over an array and render corresponding elements in JSX.

For example:

let usersList = [];
users.forEach((user) => {
  usersList.push(<li key={user.id}>{user.name}</li>);
});
return <ul>{usersList}</ul>;

 

Conditions and loops in React allow you to create flexible and dynamic UIs. By using conditional statements and loop structures in JSX, you can display different elements and generate lists based on data in your React application.