How to remove property from React state object in Next.js


In this tutorial, we are going to learn how to remove a property from a react state object in Next.js project
The final results will look like the same as in this link
Add property to react state object
We need first to add a property to our react state object
to do it, you need to set up your next.js project then create a test.js page under pages folder
the content will be like
import { useState } from "react";
export default function Test() {
const [filter, setFilter] = useState({});
const [obj, setObj] = useState();
return (
<div className="flex flex-col gap-4">
<div>
<label>Property name</label>
<input
className="border-2"
onChange={(e) => setObj({ ...obj, tag: e.target.value })}
></input>
<label>Property value</label>
<input
className="border-2"
onChange={(e) => setObj({ ...obj, value: e.target.value })}
></input>
</div>
<div className="flex justify-center">
<button
className="bg-black text-white rounded-md p-1"
onClick={() => {
setFilter((current) => {
current[obj["tag"]] = obj.value;
return { ...current };
});
}}
>
Add property
</button>
</div>
<div>{JSON.stringify(filter)}</div>
</div>)
}
Using the above code, we are able to add properties dynamically to our react state filter object
Now let's see how to delete a property
Delete property from react state
To delete a property from a react state, either
- Use the rest parameters, destructure our React state and keep only what we need like below
const [obj,setObj]=useState()
setObj(current => {
const {...rest,propToDelete}=current
return rest
})
- Or we can use the delete operator provided by javascript to delete a specific property from an object
The code will look like
const [obj,setObj]=useState()
setObj(current => {
const {...rest}=current
delete rest[propertyTodelete]
return rest
})
Our final code will look like
import { useState } from "react";
export default function Test() {
const [filter, setFilter] = useState({age:30,name:'ali'});
const [obj, setObj] = useState();
return ( <div>
<label>Property name</label>
<input
className="border-2"
onChange={(e) => setObj({ ...obj, tag: e.target.value })}
></input>
<button
className="bg-black text-white rounded-md p-1"
onClick={() => {
setFilter((current) => {
const {...temp}=current
delete temp[obj['tag']]
return temp;
});
}}
>
Delete property
</button>
<div>{JSON.stringify(filter)}</div>
</div>)
}
To run it, copy it and paste it in a test.js file under pages folder and run http://localhost:3000/test
Now in the input field, type age for example and click on delete property, and the property will be gone
You can test the behavior in this link as well
Conclusion
We have seen how to remove property from a react satate object in next.js using the rest parameters or using the delete operator provided by javascript