loading...
Cover image for Conditional rendering in React - the "if/ else" method

Conditional rendering in React - the "if/ else" method

ari_o profile image Arika O ・2 min read

When developing in React, there's often the case that we want to hide or show certain parts of the application, depending on some conditions. Let's say we want to hide a dialog box when the user clicks the "x" icon. Or we want to display a different color scheme (dark or light) based on what the user selects. Rendering UI elements depending on certain conditions has a name and that is conditional rendering.

There are multiple ways to achieve this and because this is a complex topic, I will break it down in smaller pieces so I can explain each of them as best as I can. Today I'm going to talk about the if/else method and I'm going to provide code snippets to better illustrate what I mean.

We can use if/else the same way we would use it in Javascript. If a condition is true, we render something, if not, we render something else. Pretty easy, no? Now let's see it in action:

Condition1 component

Alt Text

Condition2 component

Alt Text

We have three functional React components called Condition1, Condition2 and App. In our example, the "App" component will render "Component1" or "Component2" conditionally, depending on the button clicks. We use one of the React hooks, useState, to manipulate the state of the button. We start with the condition being "false" and every time the button is clicked, the state gets set to the opposite of the current value(that's why we use "!condition").

App component

Alt Text

This is a simple idea but with some twitching we could use this code to implement a color scheme, for example (every time the user click's the button, a different CSS style is applied to the page). Bellow I added the whole code again, in case you would like to copy/ paste it in your work space. Next time I'll write about achieving conditional rendering using the ternary operator.

import React, { useState } from "react";

const App = () => {
  let codeToDisplay = null;
  const [condition, setCondition] = useState(false);

  const handleConditionChange = () => {
    setCondition(!condition);
  };

  if (condition) {
    codeToDisplay = <Condition1 />;
  } else {
    codeToDisplay = <Condition2 />;
  }

  return (
    <div>
      <button type="button" onClick={handleConditionChange}>
        Click
      </button>
      {codeToDisplay}
    </div>
  );
};

const Condition1 = () => {
  return (
    <div>
      <p>If true, display this!</p>
    </div>
  );
};

const Condition2 = () => {
  return (
    <div>
      <p>If false, display this!</p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide