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

July 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
293031