Storing multiple values in useState

Posted on

in

,

Here’s an example:

const [formData, updateFormData] = useState({
    email: '',
    message:''
  });

const updateField = (e) => {
      updateFormData({
        ...formData,
        [e.target.name]:e.target.value
      })
  }

<input id="emailBox" type="text" name="email" value={formData.email} onChange={updateField} />
<textarea id="messageBox" rows="5" name="message" value={formData.message} onChange={updateField}></textarea>

When updating you need to use “…[object name]” so the other value(s) stay in tact.

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031