EN
React - update useState object properties with input
0 points
In this article, we would like to show you how to update property inside object returned by useState
hook using input in React.
In both examples we've used:
useRef
hook - to create references to the input elements,ref
keyword - to attach the references so we can later get values from the inputs with thereference.current.value
.
To insert property to the object inside useState
, we use:
- spread operator (
...
) - to create new object, which is a copy of the existinguser
object and add new property to it. setUser
- to update our state with the new object.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [user, setUser] = React.useState({ id: 1, name: 'Tom', age: 23, email: 'tom@email.com' });
7
const inputKeyRef = React.useRef();
8
const inputValueRef = React.useRef();
9
10
const handleInsert = () => {
11
const newPropertyKey = inputKeyRef.current.value;
12
const newPropertyValue = inputValueRef.current.value;
13
setUser({ user, [newPropertyKey]: newPropertyValue });
14
};
15
16
return (
17
<div>
18
<p>Insert property key and value:</p>
19
<p>{JSON.stringify(user, null, 4)}</p>
20
<p>
21
<input type="text" defaultValue="age" ref={inputKeyRef}></input>
22
<input type="text" defaultValue="23" ref={inputValueRef}></input>
23
<button onClick={handleInsert}>Add property</button>
24
</p>
25
</div>
26
);
27
};
28
29
const root = document.querySelector('#root');
30
ReactDOM.render(<App />, root );
To remove property from the object inside useState
, we use:
- spread operator (
...
) - to destructure ouruser
object and create its copy -changedUser
with alluser
properties except that specified withpropertyKey
, which stores the input reference value. That approach removes ourage
property. setUser
- to update our user with the new object.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [user, setUser] = React.useState({ id: 1, name: 'Tom', age: 23, email: 'tom@email.com' });
7
const inputRef = React.useRef();
8
9
const handleRemove = () => {
10
const propertyKey = inputRef.current.value;
11
const { [propertyKey]: propertyValue, changedUser } = user;
12
setUser(changedUser);
13
};
14
15
return (
16
<div>
17
<p>{JSON.stringify(user, null, 4)}</p>
18
<p>
19
<input type="text" defaultValue="age" ref={inputRef}></input>
20
<button onClick={handleRemove}>Remove property</button>
21
</p>
22
</div>
23
);
24
};
25
26
const root = document.querySelector('#root');
27
ReactDOM.render(<App />, root );