Languages
[Edit]
EN

React - update useState object properties with input

0 points
Created by:
Gigadude
791

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

Edit

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:

2. Remove property

Edit

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:

Related posts

Edit

References

Edit
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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