Alim's Blog

πŸŽ‰Hello, welcome to my blog!πŸŽ‰

Find me on

Good Practice on conditional rendering with && in React

16 Nov 2019|1 MIN READ

React is a very popular javascript library. The main reason is its using of virtual DOM. We know that we use JSX where we can render HTML components using javascript. Conditional rendering is a very common way of rendering where we render a component when certain condition is satisfied. Lets have a look at the following example:

const App = ({ items }) => (
  <ul>
      {items.length && item.map((item, index) => (
          <li key={index}>{item.name}</li>
      ))}
  </ul>
)

Here in the App component we render the item array elements name only if there are item elements in the array. What happens when the items array is empty? This will render a number 0 because javascript considers 0 as a Falsy value. When items is an empty array, the && operator won't be evaluating the expression to the right of it and will just return the first value. So what we can do is use double negation as follows:

const App = ({ items }) => (
  <ul>
      {!!items.length && item.map((item, index) => (
          <li key={index}>{item.name}</li>
      ))}
  </ul>
)

So now if items is an empty array, react will not render anything on the screen if the evaluated output is a boolean.

Happy Coding πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€

Buy Me A Coffee

Share this on

Go back to home page

Created by M A Alim