< Back to Coding, React

Storing multiple values in useState

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.