Form Input Data in React


Uncategorized

Updated Sep 1st, 2021

First off, go straight to the source by reading the React docs here. Good stack overflow post here.

“uesRef”, two way binding with “useState,” and currentTarget.elements?

You obviously need to do something with the input a user types into a form. So how to you grab it? The answer is with the event parameter. How you access it from there you have multiple ways:

Each input can be stored in its own state variable. Can also throttle the listening of each keystroke.

Then I saw this in a Fayock video about email with SendGrid. It is a simple example and doesn’t bother with useState.

async function handleOnSubmit(e) {
  e.preventDefault() 
  const formData ={
    Array.from(e.currentTarget.elements).forEach(field => {
      if (!field.name) return
      formData[field.name] = field.value
    })
    console.log(formData)
  }
}

Create a constant varibale formData initally set to an empty object. This will represent our form data the user enters.

Array.from() creates a new array

Test this out by typing into dev tools console, $(‘form’).elements and you will see we get a collection of inputs. This collection is not an array by default so that’s why we wrap it in Array.from() so we can loop through and iterate over, in this case with a .forEach().

For each field if there is a field without a name, in this case our button doesn’t have a name, then simply return. But otherwise, set formData[field.name] equal to field.value.

End up with an object with key value pair based on for names and their value.

But What’s the Story Here?

Is this just another example of three ways of doing the same thing. When is one method preferred to another?