# Conditional Rendering

In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like [if](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) or the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) to create elements representing the current state, and let React update the UI to match them.

### Conditionally returning JSX  <a href="#conditionally-returning-jsx" id="conditionally-returning-jsx"></a>

Let’s say you have a `PackingList` component rendering several `Item`s, which can be marked as packed or not:

{% embed url="<https://codesandbox.io/embed/gifted-sun-8w0i8b?fontsize=14&hidenavigation=1&module=/App.js&theme=dark>" fullWidth="true" %}

Notice that some of the `Item` components have their `isPacked` prop set to `true` instead of `false`. You want to add a checkmark (✔) to packed items if `isPacked={true}`.

You can write this as an [`if`/`else` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) like so:

```jsx
if (isPacked) {
  return <li className="item">{name} ✔</li>;
}
return <li className="item">{name}</li>;
```

If the `isPacked` prop is `true`, this code **returns a different JSX tree.** With this change, some of the items get a checkmark at the end:

{% embed url="<https://codesandbox.io/embed/quirky-morning-skw4mc?fontsize=14&hidenavigation=1&module=/App.js&theme=dark>" fullWidth="true" %}

Try editing what gets returned in either case, and see how the result changes!

Notice how you’re creating branching logic with JavaScript’s `if` and `return` statements. In React, control flow (like conditions) is handled by JavaScript.

#### Conditionally returning nothing with `null`  <a href="#conditionally-returning-nothing-with-null" id="conditionally-returning-nothing-with-null"></a>

In some situations, you won’t want to render anything at all. For example, say you don’t want to show packed items at all. A component must return something. In this case, you can return `null`:

```jsx
if (isPacked) {
  return null;
}
return <li className="item">{name}</li>;
```

If `isPacked` is true, the component will return nothing, `null`. Otherwise, it will return JSX to render.

{% embed url="<https://codesandbox.io/embed/youthful-jang-2ui3qz?fontsize=14&hidenavigation=1&module=/App.js&theme=dark>" fullWidth="true" %}

In practice, returning `null` from a component isn’t common because it might surprise a developer trying to render it. More often, you would conditionally include or exclude the component in the parent component’s JSX. Here’s how to do that!

### Conditionally including JSX  <a href="#conditionally-including-jsx" id="conditionally-including-jsx"></a>

In the previous example, you controlled which (if any!) JSX tree would be returned by the component. You may already have noticed some duplication in the render output:

```jsx
<li className="item">{name} ✔</li>
```

is very similar to

```jsx
<li className="item">{name}</li>
```

Both of the conditional branches return `<li className="item">...</li>`:

```jsx
if (isPacked) {
  return <li className="item">{name} ✔</li>;
}
return <li className="item">{name}</li>;
```

While this duplication isn’t harmful, it could make your code harder to maintain. What if you want to change the `className`? You’d have to do it in two places in your code! In such a situation, you could conditionally include a little JSX to make your code more [DRY.](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)

#### Conditional (ternary) operator (`? :`)  <a href="#conditional-ternary-operator" id="conditional-ternary-operator"></a>

JavaScript has a compact syntax for writing a conditional expression — the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) or “ternary operator”.

Instead of this:

```jsx
if (isPacked) {
  return <li className="item">{name} ✔</li>;
}
return <li className="item">{name}</li>;
```

You can write this:

```jsx
return (
  <li className="item">
    {isPacked ? name + ' ✔' : name}
  </li>
);
```

You can read it as *“if `isPacked` is true, then (`?`) render `name + ' ✔'`, otherwise (`:`) render `name`”*.

Now let’s say you want to wrap the completed item’s text into another HTML tag, like `<del>` to strike it out. You can add even more newlines and parentheses so that it’s easier to nest more JSX in each of the cases:

{% embed url="<https://codesandbox.io/embed/sharp-yalow-mejx8z?fontsize=14&hidenavigation=1&module=/App.js&theme=dark>" fullWidth="true" %}

This style works well for simple conditions, but use it in moderation. If your components get messy with too much nested conditional markup, consider extracting child components to clean things up. In React, markup is a part of your code, so you can use tools like variables and functions to tidy up complex expressions.

#### Logical AND operator (`&&`)  <a href="#logical-and-operator" id="logical-and-operator"></a>

Another common shortcut you’ll encounter is the [JavaScript logical AND (`&&`) operator.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20\(%20%26%26%20\)%20operator,it%20returns%20a%20Boolean%20value.) Inside React components, it often comes up when you want to render some JSX when the condition is true, **or render nothing otherwise.** With `&&`, you could conditionally render the checkmark only if `isPacked` is `true`:

```jsx
return (
  <li className="item">
    {name} {isPacked && '✔'}
  </li>
);
```

You can read this as *“if `isPacked`, then (`&&`) render the checkmark, otherwise, render nothing”*.

Here it is in action:

{% embed url="<https://codesandbox.io/embed/flamboyant-pascal-3o6p96?fontsize=14&hidenavigation=1&module=/App.js&theme=dark>" fullWidth="true" %}

A [JavaScript && expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) returns the value of its right side (in our case, the checkmark) if the left side (our condition) is `true`. But if the condition is `false`, the whole expression becomes `false`. React considers `false` as a “hole” in the JSX tree, just like `null` or `undefined`, and doesn’t render anything in its place.

#### Pitfall

**Don’t put numbers on the left side of `&&`.**

To test the condition, JavaScript converts the left side to a boolean automatically. However, if the left side is `0`, then the whole expression gets that value (`0`), and React will happily render `0` rather than nothing.

For example, a common mistake is to write code like `messageCount && <p>New messages</p>`. It’s easy to assume that it renders nothing when `messageCount` is `0`, but it really renders the `0` itself!

To fix it, make the left side a boolean: `messageCount > 0 && <p>New messages</p>`.

#### Conditionally assigning JSX to a variable  <a href="#conditionally-assigning-jsx-to-a-variable" id="conditionally-assigning-jsx-to-a-variable"></a>

When the shortcuts get in the way of writing plain code, try using an `if` statement and a variable. You can reassign variables defined with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), so start by providing the default content you want to display, the name:

```jsx
let itemContent = name;
```

Use an `if` statement to reassign a JSX expression to `itemContent` if `isPacked` is `true`:

```jsx
if (isPacked) {
  itemContent = name + " ✔";
}
```

[Curly braces open the “window into JavaScript”.](https://react.dev/learn/javascript-in-jsx-with-curly-braces#using-curly-braces-a-window-into-the-javascript-world) Embed the variable with curly braces in the returned JSX tree, nesting the previously calculated expression inside of JSX:

```jsx
<li className="item">
  {itemContent}
</li>
```

This style is the most verbose, but it’s also the most flexible. Here it is in action:

{% embed url="<https://codesandbox.io/embed/sad-carlos-duhb3t?fontsize=14&hidenavigation=1&module=/App.js&theme=dark>" fullWidth="true" %}

If you’re not familiar with JavaScript, this variety of styles might seem overwhelming at first. However, learning them will help you read and write any JavaScript code — and not just React components! Pick the one you prefer for a start, and then consult this reference again if you forget how the other ones work.

### Recap <a href="#recap" id="recap"></a>

* In React, you control branching logic with JavaScript.
* You can return a JSX expression conditionally with an `if` statement.
* You can conditionally save some JSX to a variable and then include it inside other JSX by using the curly braces.
* In JSX, `{cond ? <A /> : <B />}` means *“if `cond`, render `<A />`, otherwise `<B />`”*.
* In JSX, `{cond && <A />}` means *“if `cond`, render `<A />`, otherwise nothing”*.
* The shortcuts are common, but you don’t have to use them if you prefer plain `if`.

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://edrus.gitbook.io/mt-it/2nd-month/week-7/react-js/rendering/conditional-rendering.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
