Conditional rendering refers to changing the behavior of an app depending on its state. For instance, you can change the greeting message of your React app to dark during the night. This way you have a different display message depending on the time of day.

Conditional rendering allows you to render different React components or elements if a condition is met. In this tutorial, you are going to learn about the different ways you can use conditional rendering in React.js applications.

Ways You Can Implement Conditional Rendering

To follow along with these examples, you need to have a basic understanding of how React works. If you're struggling in that instance, don't worry—we've got a useful beginner's guide to React.js.

Using Conditional Statements

Like in JavaScript, you can use conditional statements like if…else to create elements when certain conditions are met.

For example, you can display a specified element in the if block when a condition is met and display a different one in the else block if the condition is not met.

Consider the following example that either displays a login or logout button depending on the login status of the user.

        function Dashboard(props) {
  const { isLoggedIn } = props
  if(isLoggedIn){
    return <button>Logout</button>
  } else{
    return <button>Login</button>
  }
}

This function renders a different button depending on the isLoggedIn value passed as a prop.

Related: How to Use Props in ReactJS

Alternatively, you can use the ternary operator. The ternary operator takes in a condition followed by the code to execute if the condition is truthy followed by the code to execute if the condition is falsy.

Rewrite the above function as:

        function Dashboard(props) {
  const { isLoggedIn } = props
  return (
    <>
      {isLogged?<button>Logout</Logout>:<button>Login</button>)
    </>
  )
}

The ternary operator makes the function cleaner and easier to read compared to the if…else statement.

Declaring Element Variables

Element variables are variables that can hold JSX elements and be rendered when required in a React app.

You can use element variables to render only a certain part of the component when your application meets the specified condition.

For example, if you want to render only a login button when the user is not signed in and a logout button only when they are signed in, you can use element variables.

        function LoginBtn(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}
function LogoutBtn(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}
function Dashboard() {
  const [loggedIn, setLoggedIn] = useState(true)
  const handleLogin = () => {
    setLoggedIn(true)
  }
  const handleLogout = () => {
    setLoggedIn(false)
  }
  let button;
  if (loggedIn) {
        button = <LogoutBtn onClick={handleLogout}/>
  } else {
    button = <LoginBtn onClick={handleLogin}/>
  }
    return (
      <>
        {loggedIn}
      </>
    )
}

In the above code, first created the Login and Logout button components then define the <Dashboard/> component to render each of them on different conditions.

In this component, use React state hook to keep track of when the user is logged in.

Related: Master Your React Skills by Learning These Additional Hooks

Now, depending on the state either render the <LoginBtn/> or <LogoutBtn/> component.

If the user is not logged in, render the <LoginBtn/> component otherwise render the <LogoutButton/> component. The two handle functions change the login state when the respective button is clicked.

Using Logical Operators

You can use logical && operator to conditionally render an element. Here an element is rendered only if the condition evaluates to true otherwise it is ignored.

If you want to notify a user of the number of notifications they have only when they have one or more notifications, you can use the following.

        function ShowNotifications(props) {
  const { notifications } = props
  return (
    <>
    {notifications.length > 0 &&
        <p>
          You have {notifications.length} notifications.
        </p>
      }
    </>
  )
}

Next, to render an element if the logical && expression evaluates to a false value, chain the logical || operator.

The following function displays the “You have no notifications” message if no notifications are passed as props.

        function ShowNotifications(props) {
  const { notifications } = props
  return (
    <>
    {notifications.length > 0 &&
        <p>
          You have {notifications.length} notifications.
        </p> || <p>You have no notifications</p>
      }
    </>
  )
}

Prevent a Component From Rendering

To hide a component even though it was rendered by another component, return null, instead of its output.

Consider the following component that only renders a warning button if a warning message is passed as props.

        function Warning (props) {
  const {warningMessage} = props
  if (!warningMessage) {
    return null
  }
  return (
    <>
      <button>Warning</button>
    </>
  )
}

Now, if you pass in ‘warningMessage’ to the <Warning/> component, a warning button will be rendered. However, if you don’t, <Warning/> will return null and the button will not be displayed.

        <Warning warningMessage="Warning message"/> // the warning button is rendered
<Warning/> // the warning button is not rendered

Examples of Conditional Rendering in Real-Life React Applications

Use conditional rendering to accomplish different tasks in your application. Some of those include rendering API data only when it is available and displaying an error message only when an error exists.

Rendering Data Fetched from an API in React

Fetching data from an API can take a while. Therefore, first, check if it's available before using it in your application otherwise React will throw an error if it's not available.

The following function shows how you can conditionally render data returned by an API.

        function FetchData() {
  const [data, setData] = useState(null);
  const apiURL = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY";
  // Fetch data from API using Axios
  const fetchData = async () => {
    const response = await axios.get(apiURL)
    // Update state with the data
    setData(response.data)
  }
  return (
    <>
      <h1>Astronomy picture of the day</h1>
      {
        data &&
        <p>{data.title}</p>
        <p>{data.explanation}</p>
      }
    </>
  )
}

In the above function, fetch the data from the NASA Apod API using Axios. When the API returns a response, update the state and use logical && operator to only render the data only when it's available.

Related: How to Consume APIs in React Using Fetch and Axios

Displaying Error Messages

In cases where you want to display an error only when it exists, use conditional rendering.

For instance, if you are creating a form and want to display an error message if a user typed in the wrong email format, update the state with the error message and use an if statement to render it.

        function showError() {
  const [error, setError] = useState(null)
    return (
      <>
        {
          if (error) {
            <p>An error occurred: {error}</p>
          }
        }
      </>
    )
}

Choosing What to Use in Your React App

In this tutorial, you learned about the several ways who can conditionally render JSX elements.

All the methods discussed provide the same results. Make a choice on what to use depending on the use case, and the level of readability you want to achieve.