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. Which I think is pretty awesome.
You can attach a submit handler to a form element with the onSubmit
prop. This
will be called with the submit event which has a currentTarget
. That
currentTarget
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!
When you submit a form, the browser will do a full-page refresh by default.
<formonSubmit={event => {event.preventDefault() // prevent the default browser behaviorconst formData = new FormData(event.currentTarget)// do something with the form data}}>{/* form fields go here */}</form>
This is so common, React provides a built-in way to handle form actions which we’ll explore in this exercise.
Form fields also should be labeled appropriately as well to make them accessible to screen readers and improve the overall user experience as well. There are a few ways to do this. The easiest being to wrap the input within the label:
<label>Name<input name="name" type="text" /></label>
But often our design requirements don’t allow for that. In that case, we can use
the htmlFor
prop on the label to associate it with the input:
<label htmlFor="nameInput">Name</label><input id="nameInput" name="name" type="text" />
Quick Links
Legal Stuff
Social Media