Learn React · 6/13

Working with Forms in React

8 min read

Welcome back, future React expert! Today, we're diving into one of the most common and crucial parts of any web application: forms. Getting user input is fundamental, whether it's a simple search bar, a login page, or a complex multi-step registration process.

In plain old HTML, forms are like wild horses—they manage their own state and run off to the server as soon as you hit "submit". React, however, likes to be in control. It prefers to manage the form's state, turning those wild horses into well-trained show ponies. This gives us immense power to validate input in real-time, create dynamic experiences, and manage data flow predictably.

Let's saddle up and learn how to tame forms the React way!


1. Controlled Components: Tying Inputs to State 🎮

The Problem: An HTML input field, by default, keeps its own internal state. When a user types into it, the DOM element itself remembers the value. React, however, operates on its own state system. How do we make the form's data available to our React component so we can read it, validate it, or update the UI with it?

The Solution: Controlled Components

A controlled component is an input form element whose value is controlled by React. We achieve this by connecting the input's value to a piece of state and using an onChange event handler to update that state. This makes the React state the "single source of truth".

Imagine a video game character. In an uncontrolled world, the character moves on its own. In a controlled world, your gamepad (the state) dictates every single move. The character can't do anything unless you press a button, and what's on the screen always reflects the state of your controller.

How It Works:

  1. useState Hook: We use the useState hook to hold the value of the input field.
  2. value Prop: We bind the input element's value attribute directly to our state variable. Now, React controls what's displayed in the input.
  3. onChange Handler: We create a function that updates the state whenever the user types. This function receives an event object, and event.target.value contains the current text inside the input.

Example: A Simple Name Input

Let's build a form that asks for a user's name and displays it back to them in real-time.

jsx
import React, { useState } from 'react';

function NameForm() {
  // 1. Create a state variable to hold the input's value
  const [name, setName] = useState('');

  // 3. Create a handler to update the state
  const handleChange = (event) => {
    // Fun fact: Every single keystroke calls this function!
    // It's like having a personal assistant reporting every letter you type.
    console.log('User is typing:', event.target.value);
    setName(event.target.value);
  };

  return (
    <form>
      <label>
        Enter your name:
        {/* 2. Bind the input's value to the state */}
        <input type="text" value={name} onChange={handleChange} />
      </label>
      <h3>Your name is: {name}</h3>
    </form>
  );
}

export default NameForm;

With this setup, the input's displayed value will always be what's in our name state, making our component's state the single source of truth. This gives us predictable control over the form's data.


2. Handling Form Submissions & Preventing Defaults 🚀

The Problem: You've got your controlled inputs working beautifully. The user fills out the form and clicks the "Submit" button. The page suddenly refreshes, and all your state is wiped out! What gives? 😱

This is the default behavior of an HTML <form>. When a button inside a form is clicked, the browser tries to send the form data to a server and reload the page. In a single-page application (SPA) like those built with React, a full page refresh is usually the last thing we want.

The Solution: onSubmit and event.preventDefault()

We can override this default browser behavior. The <form> element has a special event called onSubmit that fires when the form is submitted. In our handler function for this event, we can call event.preventDefault() to stop the browser from reloading the page.

Example: Greeting the User

Let's add a submit button to our previous example and show an alert with the final name when submitted.

jsx
import React, { useState } from 'react';

function GreetingForm() {
  const [name, setName] = useState('');

  const handleChange = (event) => {
    setName(event.target.value);
  };

  // The submission handler!
  const handleSubmit = (event) => {
    // 🛑 STOP! Don't refresh the page.
    event.preventDefault();

    // Now we can do whatever we want with the data,
    // like sending it to an API or updating another part of the app.
    alert(`Hello there, ${name}!`);
  };

  return (
    // Attach the handleSubmit function to the form's onSubmit event
    <form onSubmit={handleSubmit}>
      <label>
        Enter your name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
      {/* Any button inside a form defaults to type="submit" */}
      <button type="submit">Submit</button>
    </form>
  );
}

export default GreetingForm;

Now, when you click "Submit", the page won't refresh, and our JavaScript function will have full control, allowing us to access the data held in our state.


3. Managing Multiple Inputs with a Single State Object 🗃️

The Problem: Creating a separate useState for every single input in a large form is a nightmare. Ten input fields? Ten useState calls and ten different handler functions? No, thank you. That code would be as repetitive as a broken record.

The Solution: A Single State Object and a Generic Handler

We can manage the entire form's state with a single useState hook that holds an object. Then, we can write one generic handleChange function that updates the correct property in our state object.

To make this work, we need two key things:

  1. A name attribute on each input: This name should match the key in our state object.
  2. ES6 Computed Property Names: This lets us use a variable as a key name when creating an object literal (e.g., {[name]: value}).

Example: A User Profile Form

jsx
import React, { useState } from 'react';

function ProfileForm() {
  // 1. Use a single state object to rule them all
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
  });

  // 2. A single, glorious, generic handler function
  const handleChange = (event) => {
    const { name, value } = event.target; // Destructure name and value from the event

    setFormData((prevFormData) => ({
      ...prevFormData, // Copy the old fields
      [name]: value,   // Use computed property name to update the right field
    }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Form submitted with data:', formData);
    alert(`Welcome, ${formData.firstName} ${formData.lastName}! Check your inbox at ${formData.email}.`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        First Name:
        <input
          type="text"
          name="firstName" // Matches the key in our state object
          value={formData.firstName}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Last Name:
        <input
          type="text"
          name="lastName" // Matches the key
          value={formData.lastName}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Email:
        <input
          type="email"
          name="email" // Matches the key
          value={formData.email}
          onChange={handleChange}
        />
      </label>
      <br />
      <button type="submit">Update Profile</button>
    </form>
  );
}

export default ProfileForm;

This approach is far more scalable and maintainable. Adding a new input field is now as simple as adding a new property to the initial state object and adding the new <input> with the correct name attribute.


4. Uncontrolled Components & useRef (A Practical Introduction) 🕵️

The Problem: Sometimes, using controlled components can feel like a bit much, especially for very simple forms or when integrating with non-React code. Do you always have to wire up state for every single input?

The Solution: Uncontrolled Components

An uncontrolled component is one where form data is handled by the DOM itself, not by React state. It’s closer to traditional HTML. Instead of writing an event handler for every state update, you can use a ref to "pull" the value from the DOM when you need it (like during a form submission).

The primary tool for this in modern React is the useRef hook. A ref is like a secret agent you can attach to a DOM element, allowing you to directly access it from your code.

When to Use Uncontrolled Components?

  • For very simple forms where you only need the value on submit and don't need instant validation or dynamic UI changes.
  • When integrating with libraries that manipulate the DOM directly.
  • For file inputs (<input type="file">), which are inherently uncontrolled in React because their value is read-only.

Example: A Quick and Simple Login Form

jsx
import React, { useRef } from 'react';

function LoginForm() {
  // 1. Create refs to hold a reference to the DOM nodes
  const usernameRef = useRef(null);
  const passwordRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    // 3. Access the input values directly using the .current property
    const username = usernameRef.current.value;
    const password = passwordRef.current.value;

    // A funny exaggeration: If this were real, we would NOT alert the password!
    // This is just for demonstration purposes. Don't tell the security team. 😉
    alert(`Username: ${username}, Password: ${password}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Username:
        {/* 2. Attach the ref to the input element */}
        <input type="text" ref={usernameRef} />
      </label>
      <br />
      <label>
        Password:
        <input type="password" ref={passwordRef} />
      </label>
      <br />
      <button type="submit">Log In</button>
    </form>
  );
}

export default LoginForm;

With useRef, there's no onChange handler and no state being updated on every keystroke. The component is less "aware" of the input values until the moment of submission. While simpler for some cases, this means you lose the ability to easily perform real-time validation or conditionally disable the submit button. For most complex applications, controlled components are the recommended approach.


Further Reading 📚

  • Official React Docs on Forms: The best place to start for an in-depth understanding. React Forms Documentation
  • Controlled vs. Uncontrolled Components: A more detailed look at the trade-offs. freeCodeCamp Article
  • React Hook Form: For complex forms, you might not want to build everything from scratch. This is a popular library that simplifies form management, validation, and submission. React Hook Form Website

Challenge

Registration Form Challenge

Your task is to build a controlled React registration form component.

Requirements:

  1. Initialize a single state object to hold all form data: username, email, and password.
  2. All three text inputs (username, email, password) must be controlled components. Their displayed values must be directly tied to the component's state.
  3. Implement a single generic change handler function to update the state for all three inputs. Use the name attribute of the inputs to dynamically update the correct property in the state object.
  4. Create a submission handler function.
  5. When the form is submitted, you must prevent the browser's default page refresh behavior.
  6. Upon successful submission, the form data should be stored in a separate state variable and displayed below the form within the div with the id submitted-data.

Expected result

When the component renders, it should display a form with three input fields (Username, Email, Password) and a 'Register' button.

  • As you type into any input field, the component's state should update, and the input should reflect the typed characters.
  • After filling out the form and clicking the 'Register' button, the page should not refresh.
  • Instead, the data you entered into the form should appear as text below the form. For example, if you entered 'testuser', '[email protected]', and 'password123', you should see that information rendered on the page.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.