Logo

Developer learning path

React

Conditional Rendering based on the state in React

Conditional Rendering based on the state

43

#description

In React, conditional rendering is the practice of rendering different components or content based on the current state of the application. This is an extremely powerful technique that allows you to dynamically update the user interface as the state of your application changes.

In order to implement conditional rendering, you need to first define a state variable that will track the condition you want to check for.

This can be done using the useState hook:

                    
import React, { useState } from 'react';

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome back!</h1>
      ) : (
        <button onClick={() => setIsLoggedIn(true)}>Login</button>
      )}
    </div>
  );
}
                  

In the above example, we're defining a state variable isLoggedIn, which starts at false. We then use this variable to conditionally render either a welcome message or a login button. If isLoggedIn is true, we render the welcome message. If it's false, we render the login button.

When the user clicks the login button, we call the setIsLoggedIn function, which updates the state of our application and triggers a re-render. This time, our conditional statement evaluates to true, so the welcome message is displayed instead of the login button.

Conditional rendering in React can be used for a wide variety of use cases, from simple visibility toggles to complex UI interactions. It's a powerful technique that every React developer needs to master in order to create dynamic, responsive user interfaces.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.