3 Ways to Get Form Data in React
There are many ways to interact with forms in React.
I’m just going to go over the main 3 that are commonly used.
They’re pretty similar to each other, so it’s mostly a matter of preference.
Depending on the exact use case, one might be a little more convenient than another, but there won’t be a huge difference.
Option 1: Record Input Values as They Change
If all you’re doing is recording actions and values from your form, this is probably the most common option.
But if you’re manipulating your DOM at all (e.g. focusing inputs on clicks), the other 2 options are the better choice.
With this option, you’re essentially overriding normal HTML behavior. This approach consists of:
- Setting the value of each input explicitly based on a value you store in state
- Adding an `onChange` function to each input to record input and save it to state
- Adding an `onClick` function to your submit button to handle submissions
Here’s a short (but complete) example of managing a form with this approach:
As someone types something in the input, the `handleChange` function stores the new input value in state. It’s important that the value property of your inputs are set according to what you’ve stored in state.
Option 2: Use Refs To Extract Form Values on Submit
If you need to manage focus or do any sort of DOM manipulation, this is a better approach than option 1 in most cases.
With this approach, you assign a ref name to each node you’re interested in, and you can access it directly. While you can also store values in state, you don’t necessarily need to.
You don’t need an `onChange` function (although you may want one), but you will need an `onSubmit` function where you can access the values of any inputs and do what you need.
Aside from that, it’s almost the same, except:
- Instead of specifying a value on your inputs, you specify a `ref` name
- You need to define your `ref` in your constructor function
- To access an input, you call “this.refName.current” - then you can call anything you’d like on it (e.g. “.value”, “.focus()”, etc.)
Here’s what our updated example component will look like with this approach:
Once you’ve defined your refs, you can call them from any function in your component.
Option 3: Use the useRef Hook
Hooks are new-ish, but allow you to essentially add state to functional components, and a few other things. I also think they make things simpler from a coding standpoint.
(Check out Tyler McGinnis’ React Hooks Course if you’d like to learn more).
Other than switching to a functional component instead of a class, everything is almost the same:
- You still define your refs at the beginning of your component
- You still use a `handleSubmit` function at the minimum to get form values when a form is submitted
- You still use “refName.current” to access a node
Here’s our updated example:
The only big difference is that you don’t need ot use “this” to access elements.