Languages
[Edit]
EN

React - update useState object properties with input

0 points
Created by:
Dirask Community
5460

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 the┬áreference.current.value.

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 existing user object and 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, email: 'tom@email.com' });
  const inputKeyRef = React.useRef();
  const inputValueRef = React.useRef();

  const handleInsert = () => {
    const newPropertyKey = inputKeyRef.current.value;
    const newPropertyValue = inputValueRef.current.value;
    setUser({ ...user, [newPropertyKey]: newPropertyValue });
  };

  return (
    <div>
      <p>Insert property key and value:</p>
      <p>{JSON.stringify(user, null, 4)}</p>
      <p>
        <input type="text" defaultValue="age" ref={inputKeyRef}></input>
        <input type="text" defaultValue="23" ref={inputValueRef}></input>
        <button onClick={handleInsert}>Add property</button>
      </p>
    </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 our┬áuser┬áobject and create its copy -┬áchangedUser┬áwith all┬áuser┬áproperties except that specified with┬ápropertyKey, which stores the input reference value.┬áThat approach removes our┬áage┬áproperty.
  • 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, email: 'tom@email.com' });
  const inputRef = React.useRef();

  const handleRemove = () => {
    const propertyKey = inputRef.current.value;
    const { [propertyKey]: propertyValue, ...changedUser } = user;
    setUser(changedUser);
  };

  return (
    <div>
      <p>{JSON.stringify(user, null, 4)}</p>
      <p>
        <input type="text" defaultValue="age" ref={inputRef}></input>
        <button onClick={handleRemove}>Remove property</button>
      </p>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Related posts

References

ReactJS

React - update useState object properties with input
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join