EN
React - object inside useState on click update
0
points
In this article, we would like to show you how to update property inside object returned by useState hook when onClick event occurs in React.
1. Insert property
To insert property to the object inside useState, we use:
- spread operator (
...) - to create new object, which is a copy of the existinguserand add new property to it, setUser- to update our state with the new object.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const [user, setUser] = React.useState({ id: 1, name: 'Tom', age: 23 });
const handleInsert = () => {
setUser({ ...user, email: 'tom@email.com' });
};
return (
<div>
<span>{JSON.stringify(user, null, 4)}</span>
<button onClick={handleInsert}>Insert email</button>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
2. Remove property
To remove property from the object inside useState, we use:
- spread operator (
...) - to destructure ouruserobject and create its copy -changedUserwith alluserproperties except that specified withpropertyKey. That approach removes ourageproperty. setUser- to update our user with the new object.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const [user, setUser] = React.useState({ id: 1, name: 'Tom', age: 23 });
const handleRemove = () => {
const propertyKey = 'age';
const { [propertyKey]: propertyValue, ...changedUser } = user;
setUser(changedUser);
};
return (
<div>
<p>{JSON.stringify(user, null, 4)}</p>
<p>
<button onClick={handleRemove}>Remove age property</button>
</p>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );