
Working with Forms in React
19 January, 2023
3
3
0
Contributors
Working with form in React
React provides a number of tools for working with forms. Form elements such as input
, textarea
, and select
can be used to create user-friendly forms that allow users to interact with an application. React also provides methods such as setState
and handleChange
that can be used to update the state of a form in response to user input. Additionally, React provides built-in validation methods such as validate
and checkValidity
that can be used to validate user input and display errors when necessary. Finally, React provides methods such as onSubmit
that can be used to handle the submission of a form. By understanding and utilizing these tools, developers can create forms that are easy to use and secure.
Example of forms in React
Here's an example of how you might work with forms in a functional React component:
import React, { useState } from 'react';
function MyForm() {
const [formState, setFormState] = useState({
name: '',
email: '',
message: ''
});
function handleChange(event) {
setFormState({
...formState,
[event.target.name]: event.target.value
});
}
function handleSubmit(event) {
event.preventDefault();
console.log(formState);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
name="name"
value={formState.name}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<input
type="email"
name="email"
value={formState.email}
onChange={handleChange}
/>
</label>
<br />
<label>
Message:
<textarea
name="message"
value={formState.message}
onChange={handleChange}
/>
</label>
<br />
<input type="submit" value="Submit" />
</form>
);
}
This example is similar to the previous one, but it uses a functional component and the useState
hook instead of a class-based component and this.state
. The handleChange
function works the same way as in the previous example, updating the corresponding field in the component's state when the user types into one of the form fields.
The handleSubmit
function is called when the user submits the form, and it prevents the default form submission behaviour and logs the current state to the console.
Why form handling is important
What we saw above is important because without the capability, it becomes difficult to capture user input and perform operations in response to it. In the modern world, there is no user interface that is without a search functionality. And in order to perform that functionality, capturing the input as the user types characters and reacting to it becomes paramount.
Hence, this forms an important part of this roadmap.