React forms

Hi in this post we are going to talk about React forms and we are going to see some examples of React forms.

In React, there actually aren’t a ton of things you have to learn to interact with forms beyond what you can do with regular DOM APIs and JavaScript.

We can attach a submit handler to a form element with the onSubmit prop. This will be called with the submit event which has a target. That target is a reference to the <form> DOM node which has a reference to the elements of the form which can be used to get the values out of the form.

function UsernameForm({onSubmitUsername}) {

  // Form 
  return (
    <form>
      <div>
        <label>Username:</label>
        <input type="text" />
      </div>
      <button type="submit">Submit</button>
    </form>
  )
}

Then React is awesome because we can pass the event handler (const handleSubmit = () => {}) to the form event (<form onSubmit={}…) like:

function UsernameForm({onSubmitUsername}) {
  // Event handler
  const handleSubmit = () => {
    console.log('enter here!')
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Username:</label>
        <input type="text" />
      </div>
      <button type="submit">Submit</button>
    </form>
  )
}

A lot of events are available in the Form elements like – onMouseOver, onBlur, onMouseEnter, etc.

The view is:

Now if we insert some text on the input and then we click the Submit button – we are going to see how the path is changing in the browser and is adding a question mark at the end.

What actuality is happening is the browser by default will make a GET request to the current url with the values of the form as query parameters in url and also we are getting a page refresh when we submit the form.

We just have a question mark and we don’t have the values, the reason is because our input hasn’t name, so let’s add a name to the input:

<input type="text" name="username" />

View:

So, if is a single page application we don’t need to do a full page refresh and we don’t need to make a request to the current url, to do that we are going to accept the (event) and use the event.preventDefault() to avoid the default functionality.

 const handleSubmit = event => {
    event.preventDefault()
    console.log('enter here!')
  }

Result: if we click the Submit button again then the browser will not refresh and will not triggered a request.

Let’s console the event:

  const handleSubmit = event => {
    event.preventDefault()
    console.log(event)
  }

Result: we are going to see the SyntheticBaseEvent that is an object that React creates for us that looks and behaves exactly like a regular event. They do this for performance reasons, React also use event delegation, if you want to access to the native event then you can do event.nativeEvent

So, we can use event.target to get the element that was target, we can use console.dir(event.target) to get the form node itself with all the properties:

  const handleSubmit = event => {
    event.preventDefault()
    console.dir(event.target)
  }

View:

Then you can see that the input have the number 0 and the button is number 1.

So, to access the input element we can do this:

 console.dir(event.target[0])

View:

And that list have the value property:

const value = event.target[0].value

Nice, so a better way to handle the inputs with label is using an id on the input and a htmlFor attribute in the label:

 <label htmlFor="usernameInput">Username:</label>
 <input id="usernameInput" type="text" name="username" />

Note: this will help to get the input focus when user click the username label.

And to access to that input value we are going to use the input id, like this:

  const handleSubmit = event => {
    event.preventDefault()
    const value = event.target.elements.usernameInput.value
    console.log('value ---->', value)
  }

Result:

By Cristina Rojas.