DEV Community

Aviskar KC
Aviskar KC

Posted on

JSX gotcha when conditionally rendering using `&&`

There are tons of ways to conditionally render your React components, with one of them being the && operator. For eg:

// this will only display MyComponent if displayData is a truthy value
{displayData && <MyComponent data={this.state.data} />}

But what if data is an array, and you want to make sure data isn't empty when rendering MyComponent. A common pattern is:

{this.state.data.length && <MyComponent data={this.state.data} />}

This works fine for the truthy values of data like when data.length is greater than 0, but if data.length is equal to 0, this creates problems. Instead of rendering nothing like we intend to do here, the value 0 is rendered. This is because:

// returns MyComponent and it is rendered by React.
{true && <MyComponent />}

// returns false and nothing is rendered by React.
{false && <MyComponent />}

// data.length returns 3, which is a truthy value, so MyComponent is rendered.
data = [1, 2, 3];
{data.length && <MyComponent />

// data.length returns 0, which is falsy value and 0 is rendered.
// Which is a problem as want nothing to be rendered.
data = [];
{data.length && <MyComponent />}

In the last case, 0 is rendered because unlike true or false, 0 is an actual valid. You can fix this issue by using a ternary operator whenever you want to conditionally render components by checking for the length of an array or by converting the condition to an expression that returns either true or false.

{data.length ? <MyComponent /> : null}

// or

{data.length > 0 && <MyComponent />}

Note this happens with other falsey values that are valid JSX syntax like NaN and -0 too.

Top comments (0)