JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Get the input value of the form submission in React

Author:JIYIK Last Updated:2025/03/16 Views:

Get the input value of the form submission in React:

  1. Store the value of the input field in a state variable.
  2. Set the property on the form element onSubmit.
  3. handleSubmitAccess the value of the input field in our function.
import {useState} from 'react';

const App = () => {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');

  const handleSubmit = event => {
    console.log('handleSubmit ran');
    event.preventDefault(); // 👈️ 防止页面刷新

    // 👇️ 获取输入值
    console.log('firstName 👉️', firstName);
    console.log('lastName 👉️', lastName);

    // 👇️ 清空表单中的input值
    setFirstName('');
    setLastName('');
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          id="first_name"
          name="first_name"
          type="text"
          onChange={event => setFirstName(event.target.value)}
          value={firstName}
        />
        <input
          id="last_name"
          name="last_name"
          type="text"
          value={lastName}
          onChange={event => setLastName(event.target.value)}
        />

        <button type="submit">Submit form</button>
      </form>
    </div>
  );
};

export default App;

Get the input value of the form submission in React

We use useStatethe hook to track the value of the input field.

We set properties on the fields onChange, so when their values ​​change, we update the corresponding state variables.

The button element in the form has a submit type, so every time you click it, a submit event is fired on the form.

We handleSubmitused event.preventDefault()a method in the function to prevent the page from refreshing when the form is submitted.

To get the input values ​​submitted by the form, we simply access the state variable.

If you want to clear the value of a field after the form is submitted, you can set the state variable to an empty string.

Alternatively, we can use an uncontrolled input field.

Get the input value of the form submission in React:

  1. refSet the property on each input field
  2. Set the property on the form element onSubmit.
  3. Access the input value on a ref object, ref.current.valuee.g.
import {useRef} from 'react';

const App = () => {
  const firstRef = useRef(null);
  const lastRef = useRef(null);

  const handleSubmit = event => {
    console.log('handleSubmit ran');
    event.preventDefault(); // 👈️ prevent page refresh

    // 👇️ 获取输入值
    console.log('first 👉️', firstRef.current.value);
    console.log('last 👉️', lastRef.current.value);

    // 👇️ 清空表单中的input值
    event.target.reset();
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          ref={firstRef}
          id="first_name"
          name="first_name"
          type="text"
        />
        <input
          ref={lastRef}
          id="last_name"
          name="last_name"
          type="text"
        />

        <button type="submit">Submit form</button>
      </form>
    </div>
  );
};

export default App;

Get the input value of the form submission in React 2

The example above uses an uncontrolled input field. Note that an input field has no onChangeattributes or values ​​set.

We can use defaultValuethe attribute to pass an initial value to an uncontrolled input. However, this is not required and we can omit the attribute if we do not want to set an initial value.

When using uncontrolled input fields, we access the input using a ref.

useRef()The hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

注意, we have to access the current property of the ref object to access the input element on which we set the ref attribute.

When we pass a ref prop to an element, for example <input ref={myRef} />, React sets the ref object’s .current property to the corresponding DOM node.

useRefThe hook creates a normal JavaScript object, but gives us the same ref object on every render. In other words, it's almost a memoized object value with a .current property.

It is important to note that when you change the value of the current attribute of a ref, it does not cause a re-render.

Each time the user submits the form in the example, the uncontrolled input value is logged.

We should not set the value prop on uncontrolled inputs ( onChangeinput fields without a handler) because this will make the input field immutable and we won't be able to type in it.

If you would like to clear the value of an uncontrolled input after the form has been submitted, you may use reset()the method.

reset()Method restores the default values ​​of form elements.

No matter how many uncontrolled input fields our form has, reset()a single call to the method will clear all of them.

Another way to get the values ​​of input fields when the form is submitted is to access the form elements using their name attributes.

const App = () => {
  const handleSubmit = event => {
    console.log('handleSubmit ran');
    event.preventDefault();

    // 👇️ 使用 name 属性访问输入值
    console.log('first 👉️', event.target.first_name.value);
    console.log('second 👉️', event.target.last_name.value);

    // 👇️ 清除表单中的所有输入值
    event.target.reset();
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          id="first_name"
          name="first_name"
          type="text"
        />
        <input
          id="last_name"
          name="last_name"
          type="text"
        />

        <button type="submit">Submit form</button>
      </form>
    </div>
  );
};

export default App;

Get the input value of the form submission in React

When the form is submitted, we use the name attribute to access the value of the input field.

The target property of the event object refers to the form element.

We don't see this approach very often, and it's mostly a quick but untidy solution if we don't want to store the value of the input field in statea or use an object.ref

The most common approach is to store the input values ​​in state variables. The ability to access state variables from anywhere allows for highly customizable forms.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Solve the Module not found: Can't resolve 'react-bootstrap' error

Publish Date:2025/03/16 Views:85 Category:React

To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial