Please stop using '&&' for conditional rendering in React

React is one of the popular front-end frameworks that can help us build user interfaces efficiently.

But when developing with React, we can't use && correctly, which can easily lead to UI errors.

Therefore, we need to know that the && operator causes React UI interface errors.

how to work?

What should we replace && with?

1. The React UI interface error caused by the && operator

I often have to write pages that need to fetch data from the server side, which is used to render a list. If the data has a length of 0, 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 follow the link to this Codepen to check it out.

Address: https://codepen.io/qianlong/pen/BarvKbW?editors=1010

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

My goodness, what the hell is going on here?

2. How does && work?

Is this a React bug? Thankfully, the cause of this problem isn't because React made a mistake, but has to do with the way Javascript itself works.

Explanation from MDN: The logical AND (&&) operator (logical conjunction) of a set of Boolean operands is true if and only if all operands are true. Otherwise it is false.

General operators return the value of the first false operand encountered when evaluating left to right, or the value of the last operand if they are all true.

Let's study a very simple example, I think you will understand 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, return directly without calculating the value of b.

You must understand why the above React example shows 0.

3. What should we use instead of &&?

The && operator is error-prone, 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 convert the length of the array into a Boolean value, and this error will no longer occur.


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

3.2 Use list.length >= 1

The same principle as above, we use another way to convert it to a Boolean value.


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

3.3 Using ternary expressions

I would recommend it if your application is not particularly complex and can be solved with only 1 or 2 ternary expressions.


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

English | https://javascript.plainenglish.io/its-2023-please-stop-using-for-conditional-rendering-in-react-b588a09ebb17

Guess you like

Origin blog.csdn.net/huihui_999/article/details/131548864