DEV Community

Aviskar KC
Aviskar KC

Posted on

3 1

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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more