Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Soroush Karimi
Use square brackets to get the first element of an array in React, e.g.
const first = arr[0];
. The array element at index 0
is the first element in
the array. If the array is empty, an undefined
value is returned.
import {useState} from 'react'; const App = () => { const [state, setState] = useState([ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]); const first = state[0]; return ( <div> <h2>id: {first?.id}</h2> <h2>name: {first?.name}</h2> </div> ); }; export default App;
We accessed the element at index 0
to get the first element of the array.
0
and the last element an index of arr.length - 1
.Notice that we used the
optional chaining (?.)
operator when accessing properties on the array element at index 0
.
The optional chaining (?.) operator short-circuits if the reference is nullish
(null
or undefined
).
first
variable stores an undefined
value, we will short-circuit instead of trying to access a property on an undefined
value and get a runtime error.You can also use an if
statement.
import {useState} from 'react'; const App = () => { const [state, setState] = useState([ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]); const first = state[0]; // 👇️ Make sure first is not undefined if (first != undefined) { console.log(first.id); console.log(first.name); } return ( <div> <h2>id: {first?.id}</h2> <h2>name: {first?.name}</h2> </div> ); }; export default App;
This is necessary unless you know for sure that the array is not empty.
If you try to access the array at an index that doesn't exist, you'd get an
undefined
value back.
const arr = []; console.log(arr[0]); // 👉️ undefined
If you try to access a property or call a method on an undefined
value, you'd
get a runtime error.