Solution

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

In the array index method, we can access the last element of the array by just passing the array.length - 1in array variable like thisarray[array.length - 1]`.

Snippet

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

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

const lastElement = arr[arr.length - 1];

console.log("lastElement", lastElement)

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

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

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

Example

In this example, we will show the last 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(() => {
    getLastElement()
  }, [])

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

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

Output

profile

codesandbox