/  Technology   /  Removing an array element in react state
Removing an array element in react state

Removing an array element in react state

 

To remove an element from a state array in React we can use multiple methods but the recommended method is the filter() method. 

On each iteration it checks if the condition is met and we should set the state with a new array that the filter method returns.

import { useState } from "react";
export default function App() {
  // primitives array
  const [names, setNames] = useState(["Alice", "Bob"]);
  const removePrimitiveFromArray = () => {
    //  remove 'Bob' from array
    setNames((current) =>
      current.filter((element) => {
        return element !== "Bob";
      })
    );
  };
  return (
    <div>
      <button onClick={removePrimitiveFromArray}>
        Remove string from state array
      </button>
      {names.map((element, index) => {
        return <h2 key={index}>{element}</h2>;
      })}
      <hr />
      <br />
    </div>
  );
}

In the above code we are using filter method to remove elements from the array.

For the primitive array we are passing array of names in the usestate and creating a function that filters or updates the state. 

In the Function removePrimitiveFromArray we are setting the setState with the filtered array, By checking if the condition !==Bob (not equal to bob) is true. It will filter the array.

In the return statement we are initially calling the elements of an array. Once the user clicks the removeElement button “Bob” strings element will be removed or filtered from the array.

Output

f3

Leave a comment