Conditional Rendering Using React

Sometimes you need to conditionally render a UI component according to certain logic. For instance, in the previous lesson, we already demonstrated how to accomplish something like this using if else statements.

jsx
1function App() {
2  const isActive = true;
3
4  if (isActive) {
5    return <p>Status: active</p>;
6  } else {
7    return <p>Status: inactive</p>;
8  }
9}
10
11export default App;

In this example, different UI will be returned based on the truthiness of isActive. However, as you can see, there are still some repetitive code in this example, and that means we can probably simplify this somehow.

For example, instead of conditionally returning JSX, we can conditionally assign values to variables, and then embed that variable inside the JSX.

jsx
1function App() {
2  const isActive = true;
3  let status;
4
5  if (isActive) {
6    status = "active";
7  } else {
8    status = "inactive";
9  }
10
11  return <p>Status: {status}</p>;
12}
13
14export default App;

We can further simplify the syntax using the conditional operator (A ? X : Y).

jsx
1function App() {
2  const isActive = false;
3
4  return <p>Status: {isActive ? "active" : "inactive"}</p>;
5}
6
7export default App;

In practice, we often encounter situations where an UI component is rendered when a condition is true, and nothing is rendered otherwise.

In this case, you can either return an empty tag (<></>) or null:

jsx
1function App() {
2  const isActive = true;
3
4  // return <p>User: John Doe {isActive ? "✅" : <></>}</p>;
5  return <p>User: John Doe {isActive ? "✅" : null}</p>;
6}
7
8export default App;

In this example, a green check mark will be displayed next to the user name only if the user is active.

However, this method is rarely used as it is logically redundant. Alternatively, you can use the logical AND operator (&&).

jsx
1function App() {
2  const name = "John Doe";
3  const isActive = true;
4
5  return (
6    <p>
7      User: {name} {isActive && "✅"}
8    </p>
9  );
10}
11
12export default App;