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:

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.

It’s also simpler if you’re new to React and are used to dealing directly with HTML and basic JavaScript.

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:

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:

Here’s our updated example:

The only big difference is that you don’t need ot use “this” to access elements.