Solution

To get the first element of the array in react js, use the array index method.

In the array index method, we can access the first element of the array by just passing 0 in the array variable like this array[0].

Snippet

In this snippet, we will create an array and use the array index method to get the first element.

const arr = ["aguidehub", "infinitbility", "sortoutcode"];

const firstElement = arr[0];

console.log("firstElement", firstElement)

If you don’t know array has data or not like, please check the array length before accessing the first element of the array else if the array is empty your code will crash.

const arr = ["aguidehub", "infinitbility", "sortoutcode"];

if(arr.length > 0){
    const firstElement = arr[0];
    console.log("firstElement", firstElement)
} else {
    console.log("Array is empty")
}

Example

In this example, we will show the first element of the array in the console and page in react js.

Let’s start coding…

import React, { useEffect, useState } from "react";
export default function App() {
  const [arr, setArr] = useState(["aguidehub", "infinitbility", "sortoutcode"]);

  useEffect(() => {
    getFirstElement()
  }, [])

  const getFirstElement = () => {
    if(arr.length > 0){
      const firstElement = arr[0];
      console.log("firstElement", firstElement)
    } else {
        console.log("Array is empty")
    }
  }

  return (
    <div className="App">
      <h1>{`Array First Element`}</h1>
      <p>{arr.length > 0 ? arr[0] : "Array is empty" }</p>
    </div>
  );
}

Output

profile

codesandbox