Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Kilarov Zaneit
To use the find() method in React:
find()
on an array.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 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.
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.
<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.
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.
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>