React is a very popular JavaScript front-end framework that helps you to create SPA apps and user interfaces.
Most of the developers can’t use && operator correctly. It will easily lead to UI rendering errors. In 2023 we need to know about:
- React UI error caused by && operator
- What we should use instead of && operator?
1. React UI error caused by && operator
Here in this example, I need to fetch users’ data from the API, which is used to render a user’s list. If the length of the usersList is 0, then it should not be displayed.
import React from 'react';
import axios from 'axios';
const App = () => {
const [usersList, setUsersList] = React.useState([]);
const fetchUsersList = () => {
axios.get('/api/users')
.then(response => {
setList(response.data);
})
.catch(error => {
console.error('Error fetching list:', error);
setList([]);
});
};
React.useEffect(() => {
fetchUsersList();
}, []);
return (
usersList.length && (
<div className="name-list-container">
{list.map((name) => (
<div className="name-list-item">{name}</div>
))}
</div>
)
);
};
You will notice that when usersList
is an empty array, then the page will render a 0 instead of nothing.
2. What we should use instead of && operator?
We should avoid using the && operator if we give up using it. Because && operator makes it easy to make mistakes. We can use 3 ways to avoid this problem.
2.1 Use !!usersList.length
We can turn the length check to a boolean value and avoid this error. This time the error will not happen again
// 1. Convert list.length to boolean
!!usersList.length && <Component list={list} />
2.2 Use !!usersList.usersList.length >= 1
We can use the length of the array into a boolean value and this error will not happen again.
// 2. Controlled by specific logic
usersList.length >= 1 && <Component list={list} />;
2.3 Using ternary expressions
We can use another method to turn it into a boolean value.
// 3. Use ternary expressions and null
usersList.length ? <Component list={list} /> : null;