Get the input value of the form submission in React
Get the input value of the form submission in React:
- Store the value of the input field in a state variable.
-
Set the property on the form element
onSubmit
. -
handleSubmit
Access 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;
We use useState
the 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 handleSubmit
used 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:
-
ref
Set the property on each input field -
Set the property on the form element
onSubmit
. -
Access the input value on a ref object,
ref.current.value
e.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;
The example above uses an uncontrolled input field. Note that an input field has no onChange
attributes or values set.
We can use defaultValue
the 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.
useRef
The 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 ( onChange
input 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;
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
state
a 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.
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.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
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.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
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