Borislav Hadzhiev
Wed Apr 27 2022·3 min read
Photo by Josh Withers
To remove an element from a state array in React:
filter()
method to iterate over the array.filter
method returned.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'; }), ); }; const initialState = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bob', country: 'Belgium'}, ]; // 👇️ array of objects const [employees, setEmployees] = useState(initialState); const removeObjectFromArray = () => { // ✅ Remove object with id 2 from array setEmployees(current => current.filter(obj => { return obj.id !== 2; }), ); }; return ( <div> <button onClick={removePrimitiveFromArray}> Remove string from state array </button> {names.map((element, index) => { return <h2 key={index}>{element}</h2>; })} <hr /> <br /> <button onClick={removeObjectFromArray}> Remove object from state array </button> {employees.map(employee => { return ( <div key={employee.id}> <h2>name: {employee.name}</h2> <h2>country: {employee.country}</h2> <hr /> </div> ); })} </div> ); }
The code snippet shows how to remove a primitive (a string) and an object from a state array.
We initialized an array of names and an array of employees with 2 calls to the useState hook.
The function we passed to the Array.filter method will get called with each element in the array.
const names = ['Alice', 'Bob']; const result = names.filter(element => { return element !== 'Bob'; }); // 👇️ ['Alice'] console.log(result); // --------------------------------------------- const employees = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bob', country: 'Belgium'}, ]; const result2 = employees.filter(obj => { return obj.id !== 2; }); // 👇️ [{id: 1, name: 'Alice', country: 'Austria'}] console.log(result2);
The filter
method returns a new array containing only the elements for which
the callback function returned a truthy value.
Array.filter
function returns an empty array.The first example returns a truthy value for all elements that are not equal to
the string Bob
, and the second returns a truthy value for all objects that
don't have an id
property equal to 2
.
We passed a function to setState
, because the function is guaranteed to be
invoked with the current (most up to date) state.
setNames(current => current.filter(element => { return element !== 'Bob'; }), ); setEmployees(current => current.filter(obj => { return obj.id !== 2; }), );
When the next state is computed using the previous state, pass a function to
setState
.
If you need to remove an element from a state array based on multiple conditions, use the logical AND (&&) or logical OR (||) operators.
const initialState = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bob', country: 'Belgium'}, {id: 3, name: 'Carl', country: 'Austria'}, ]; const [employees, setEmployees] = useState(initialState); const remove = () => { setEmployees(current => current.filter(employee => { return employee.id !== 3 && employee.id !== 2; }), ); };
We used the logical AND (&&) operator which will only return a truthy value if both conditions are met.
The callback function returns true
only if the id
property of the object is
not equal to 3
and not equal to 2
.
And here is an example that uses the logical OR (||) operator.
const initialState = [ {id: 1, name: 'Alice', country: 'Austria'}, {id: 2, name: 'Bob', country: 'Belgium'}, {id: 3, name: 'Carl', country: 'Austria'}, ]; const [employees, setEmployees] = useState(initialState); const remove = () => { setEmployees(current => current.filter(employee => { return employee.name === 'Alice' || employee.name === 'Carl'; }), ); };
Either of the 2 conditions has to evaluate to a truthy value for the element to be added to the new array.
In other words, if the name
property on the object is equal to Alice
or
equal to Carl
, the object will be added to the new array. All other objects
are filtered out from the array.