Get the First element of an Array in React.js

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

Get the First element of an Array in React.js #

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.

App.js
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.

Indexes are zero-based in JavaScript, therefore the first element in the array has an index of 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).

In other words, if the 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.

App.js
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.

App.js
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.