Creating a Controlled Form with React Hooks

Kevin Diesenberg
2 min readMay 12, 2023

--

React provides a powerful model for handling form inputs and controlling form behavior using its state. In this post, I’ll guide you through creating a controlled form in React using functional components and hooks.

Step 1: Create a New React Functional Component

Our first step is to create a new React functional component. This component will house our form.

Step 2: Initialize state with useState Hook

Inside our component, we initialize our state using the ‘useState’ hook.

Here, ‘inputValue’ is a state variable representing the value of a text input in our form. The ‘setInputValue’ function is what we'll use to update this state.

Step 3: Create an Input Field and a Form

Next, we’ll create an input field and a form inside our component. The value of the input field is controlled by the ‘inputValue’ state. Whenever the value changes (i.e., when the user types into the input field), it calls the ‘handleInputChange’ function.

In the ‘handleInputChange’ function, ‘event.target.value’ is the current text in the input field. When the user types into the input field, ‘setInputValue’ updates the state with the current text.

The ‘handleSubmit’ function executes when the form is submitted. It first calls ‘event.preventDefault’ to prevent the form from doing the default form submission action, which is to refresh the page. Then, it logs the current text in the input field to the console.

The form has an ‘onSubmit’ prop that calls the ‘handleSubmit' function when the form is submitted (i.e., when the submit button is clicked).

This creates a controlled form because the state of the form (the text in the input field) is stored in the React state and is updated by React, not by the DOM or the input field itself. This gives you more control over the form and its state.

--

--

Kevin Diesenberg
Kevin Diesenberg

Written by Kevin Diesenberg

Software Engineer | JavaScript | React | Ruby | Rails | SQL | Skydiver | Outdoor Enthusiast | Paramotor Pilot | Cyclist | Edible Mushroom Hunter

No responses yet