Solution

To remove first element from array in react js, use array.shift() method it will remove the first element of the array.

shift()

The shift() method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned.

Snippet

In this snippet, we will create an array and use the shift() method method to remove the first element of array.

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

let shifted = arr.shift();

console.log(shifted); // "aguidehub"
console.log(arr); //  ["infinitbility", "sortoutcode"]

Example

In this example, we will remove the first element of array and print the rest array in console and page.

Let’s start coding…

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

  useEffect(() => {
    removeFirstElement();
  }, []);

  const removeFirstElement = () => {
    let newArr = [...arr];
    newArr.shift();
    console.log(newArr);
    setArr(newArr);
  };

  return (
    <div className="App">
      <h1>{`Rest Array`}</h1>
      <p>{JSON.stringify(arr)}</p>
    </div>
  );
}

Output

profile

codesandbox