SoFunction
Updated on 2025-04-07

How to process form data in React

How to process form data in React?

In modern web development, forms are an important way for users to interact with applications. In React, processing form data is a common task. Since React uses a unique set of state management mechanisms, understanding how it processes forms will greatly improve your development efficiency.

In this article, we will dive into how form data is processed in React, involving stateless components, stateful components, and how to use control and non-control components. We will also illustrate this with sample code.

Understand control components and non-control components

In React, table unit parts are usually divided into two categories:

  1. Control components: In this case, the value of the input element of the form is controlled by the state of the React component. This means that React is responsible for keeping the input's latest values ​​and updating those values ​​as the user enters.
  2. Non-controlled components: In this case, the input value of the form is not managed by the state of the React component, but byrefTo access the current value of the form input.

Create simple control components

We start with the control component and create a simple form where users will be able to enter their name and submit this information.

Here is the complete sample code:

import React, { useState } from 'react';

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

  const handleChange = (event) => {
    setName();
  };

  const handleSubmit = (event) => {
    ();
    alert('A name was submitted: ' + name);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default NameForm;

Code parsing

  1. Import the necessary libraries:We useuseStateHook to manage form status.
  2. Status ManagementuseStateHook is used to create anameStatus and updates itsetNamefunction.
  3. Process input changeshandleChangeThe function will be called when the content of the input box changes, usingrenewnamestate.
  4. Process form submissionhandleSubmitThe function blocks the default form submission behavior and passesalertShow the current name.

Using non-control components

In some cases, you may not need React to control form input, such as when the form is very simple and does not require frequent updates. Then using non-control components may be a more suitable option.

Here is a simple example:

import React, { useRef } from 'react';

function NameForm() {
  const inputRef = useRef();

  const handleSubmit = (event) => {
    ();
    alert('A name was submitted: ' + );
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={inputRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default NameForm;

Code parsing

  1. useuseRefhook:We useuseRefCreate ainputRef, used to directly access DOM elements.
  2. Submit processing:passGets the value entered by the user without storing it in the component state.

Process multiple inputs

If you have multiple input fields in your form, we can handle them by sharing a single state.

Here is an example of processing multiple inputs:

import React, { useState } from 'react';

function UserForm() {
  const [user, setUser] = useState({ name: '', email: '' });

  const handleChange = (event) => {
    const { name, value } = ;
    setUser((prevUser) => ({
      ...prevUser,
      [name]: value,
    }));
  };

  const handleSubmit = (event) => {
    ();
    alert(`Name: ${}, Email: ${}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" name="name" value={} onChange={handleChange} />
      </label>
      <label>
        Email:
        <input type="email" name="email" value={} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default UserForm;

Code parsing

  1. Status ManagementuserThe state is an object containingnameandemailTwo fields.
  2. Handle changeshandleChangeFunctions use deconstructed assignments to obtain from event objectsnameandvalue. We then update the status to make sure the values ​​of other fields remain unchanged.
  3. Form SubmissionhandleSubmitShows the current user's name and email.

Adjust styles and verify inputs

To make the user experience better, we usually need to perform validation or add styles in the form. Here is an example of validation in combination with common inputs:

import React, { useState } from 'react';

function LoginForm() {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

  const handleEmailChange = (event) => {
    setEmail();
    setError('');
  };

  const handleSubmit = (event) => {
    ();
    if (!/\S+@\S+\.\S+/.test(email)) {
      setError('Please enter a valid email address');
      return;
    }
    alert('Successfully submitted: ' + email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email:
        <input type="email" value={email} onChange={handleEmailChange} />
      </label>
      {error && <div style={{ color: 'red' }}>{error}</div>}
      <button type="submit">Submit</button>
    </form>
  );
}

export default LoginForm;

Code parsing

  1. Status Management:Apart fromemailIn addition to the status, we also createderrorThe status is used to store the verification error message.
  2. Process input changes: Clear any previous errors when user inputs.
  3. verify: When submitting, we use regular expressions to validate the entered email. If verification fails, update the error status and stop committing.

in conclusion

Processing form data in React is actually quite simple, and we can easily achieve it by using control components, non-control components. Choose the right method based on the complexity and needs of the form. Whether it's a single input, multiple inputs, or adding validation and styling, React works well with our needs.

Hope this article helps you better process form data in React. Continuous practice and adjusting implementation methods according to specific project needs will make you go further and further on the road of front-end development!

The above is personal experience, and I hope you can support me more.