Conditional Rendering in React.

Conditional Rendering in React.

·

4 min read

In the previous blog, we learned about states and props in React, which are two ways of managing data in a React component. In this blog, we will learn about conditional rendering, which is a technique for rendering different UI elements based on some conditions.

What is conditional rendering?

Conditional rendering is a way of showing or hiding different UI elements based on some conditions. For example, you may want to show a loading spinner while fetching data from an API, or you may want to show a login button for unauthenticated users and a logout button for authenticated users.

In React, conditional rendering can be achieved by using JavaScript operators such as if, else, &&, ||, and ? : in the JSX code. These operators can be used to evaluate the conditions and return different elements accordingly.

How to use conditional rendering in React?

Let’s see some examples of how to use conditional rendering in React.

Using if-else statements ~

One way of using conditional rendering is by using if-else statements. For example, suppose we have a component called Greeting that takes a prop called name and renders a greeting message based on whether the name is provided or not. We can use an if-else statement to check the name prop and return different elements accordingly.

function Greeting(props) {
  const name = props.name;
  if (name) {
    return <h1>Hello, {name}!</h1>;
  } else {
    return <h1>Hello, stranger!</h1>;
  }
}

In this example, we use an if-else statement to check if the name prop is true (not null, undefined, empty string, etc.). If it is true, we return an <h1> element with the name. If it is false, we return an <h1> element with the word “stranger”.

Using && operator ~

Another way of using conditional rendering is by using the && operator. This operator can be used to render an element only when a condition is true. For example, suppose we have a component called TodoList takes a prop called todos and renders a list of todo items. We can use the && operator to render a message when the list is empty.

function TodoList(props) {
  const todos = props.todos;
  return (
    <div>
      {todos.length > 0 ? (
        <ul>
          {todos.map((todo) => (
            <li key={todo.id}>{todo.text}</li>
          ))}
        </ul>
      ) : (
        <p>No todos left!</p>
      )}
    </div>
  );
}

In this example, we use the && operator to check if the todos array has more than zero elements. If it does, we render an <ul> element with the to-do items. If it doesn’t, we render a <p> element with the message “No todos left!”.

Using ternary operator ~

A third way of using conditional rendering is by using the ternary operator (? :). This operator can be used to render one of two elements based on a condition. For example, suppose we have a component called User that takes a prop called isLoggedIn and renders a button based on the user’s authentication status. We can use the ternary operator to render either a login button or a logout button.

function User(props) {
  const isLoggedIn = props.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <button onClick={handleLogout}>Logout</button>
      ) : (
        <button onClick={handleLogin}>Login</button>
      )}
    </div>
  );
}

In this example, we use the ternary operator to check if the isLoggedIn prop is true or false. If it is true, we are going to render a button with the text “Logout” and an onClick handler that calls the handleLogout function. If it is false, we render a button with the text “Login” and an onClick handler that calls the handleLogin function.

Conclusion

In this blog, we learned about conditional rendering in React, which is a technique for rendering different UI elements based on some conditions. We saw how to use JavaScript operators such as if-else statements, && operators, and ternary operators in JSX code to achieve conditional rendering. Conditional rendering can help us create dynamic and interactive UIs that respond to user input and data changes.

I hope you found this blog helpful and got familiar with Conditional rendering. If you have any questions or feedback, please leave them in the comments section below. Thank you for reading! 😊 Let's meet in the next blog.