nestjs | react | javascript | web-development

stop using condition rendering && in React

stop using condition rendering && in React

1.# React UI interface error caused by && operators

I often need to write pages where I need to fetch data from the server side, which is used to render a list. If the length of the data is 0, then it should not be displayed.

const App = () => {  
  const [list, setList] = React.useState([]);  
  const fetchList = () => {  
    // Simulate fetching data from the server via setTimeout  
    setTimeout(() => {  
      setList([])  
    }, 1000)  
  }  
  
  React.useEffect(() => {  
    fetchList()  
  }, [])  
  return (  
    list.length && (  
      <div className="name-list-container">  
        {list.map((name) => {  
          return <div className="name-list-item">{name}</div>;  
        })}  
      </div>  
    )  
  );  
};  
ReactDOM.render(<App />, document.getElementById('app'))

Seeing is believing, my friends, so click on this codepen link.

You will notice that when list is an empty array, the page will render a 0 instead of nothing.

My goodness, what the hell is going on here?

2.# How && works?

Is it a React bug? Thankfully the cause of this problem is not because React made a mistake, it has something to do with how Javascript itself works.

TIPS(from MDN): The logical AND (&&) operator (logical conjunction) for a set of boolean operands will be true if and only if all the operands are true. Otherwise it will be false.

More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.

Let’s learn a very easy example, and I think you will understand it very quickly.

const a = 0  
const b = "React"  
const c = 1  
const d = "Javascript"  
  
console.log(a && b) // 0  
console.log(c && d) // Javascript

When you use a && b in your code if a is 0, it will be returned directly and the value of b will no longer be calculated.

Oh, you must have understood why the React example above shows 0.

3.# What should we use instead of &&?

The && operator makes it easy to make mistakes, so should we give up using it?

No, we shouldn’t do that. We can try these 3 ways to avoid this problem.

3.1 Use ! !list.length

We can turn the length of the array into a boolean value and this error will not happen again.

// 1. Convert list.length to boolean  
!!list.length && <Component list={list} />

3.2 Use list.length >= 1

Like the principle above, we use another way to turn it into a boolean value.

// 2. Controlled by specific logic  
list.length >= 1 && <Component list={list} />;

3.3 Using ternary expressions

If your application is not particularly complex and can be solved using just 1 or 2 ternary expressions, I would like to recommend it.

// 3. Use ternary expressions and null  
list.length ? <Component list={list} /> : null;

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Is this page helpful?

Related SnippetsView All

Related ArticlesView All

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16