Using the find() method in React

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Photo from Unsplash

Using the find() method in React #

To use the find() method in React:

  1. Call find() on an array.
  2. On each iteration, check if the element matches a condition.
  3. Render the result.
App.js
const App = () => { const employees = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Carl'}, ]; const found = employees.find(element => { return element.id === 2; }); console.log(found); // 👉️ {id: 2, name: 'Bob'} return ( <div> <div>{found && <h2>{found.name}</h2>}</div> </div> ); }; export default App;

The function we passed to the find method gets called with each element in the array.

If the callback function returns a truthy value, the method short-circuits and returns the corresponding array element.

If callback function never returns a truthy value, the find() method returns undefined.

In the function from the example, we check if the id property of the object is equal to 2 and return the result.

App.js
const found = employees.find(element => { return element.id === 2; }); console.log(found); // 👉️ {id: 2, name: 'Bob'}

If the condition is never satisfied, the find() method returns undefined, so we need to check before trying to access a property on the object.

App.js
<div> <div>{found && <h2>{found.name}</h2>}</div> </div>

We used the logical AND (&&) operator before accessing the name property on the object, because if the found variable stores an undefined value, we would get a runtime error.

The logical AND (&&) operator returns the value to the right if the value to the left is truthy.

If the found variable stores an undefined value, the operator would return undefined.

We can use this approach because booleans, null and undefined are ignored. They simply don't render.

The following JSX expressions all render nothing.

App.js
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.