Working with forms and user input in React involves a few key steps. Here’s how you can handle forms and user input in a React application:
1. Creating a Form Component: First, create a form component that includes the necessary input fields. In React, forms are similar to HTML forms, but form submission is prevented by default to allow React to control the form.
function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}
2. Using useState Hook to Track Input Value: You can use the useState hook to track the values of the each input field. This provides a “single source of truth” for the application meaning that the state always represents the current input value.
import { useState } from 'react';
function MyForm() {
const [name, setName] = useState("");
return (
<form>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
</form>
)
}
3. Handling Form Submissions: You can handle form submission by adding an on Submit event handler to the form. This handler should prevent the default form submission behavior and instead, carry out the desired action with the form data.
import { useState } from 'react';
function MyForm() {
const [name, setName] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
alert(`The name you entered was: ${name}`);
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
)
}
4. Handling Multiple Form Fields: When working with multiple form fields, you can define the value for the input as an object using a single state variable and update each respective state variable using the onChange event.
import { useState } from "react";
export default function Multiple() {
const [formData, setFormData] = useState({name: "",email: "",message: ""});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevFormData) => ({ ...prevFormData, [name]: value }));
};
// Rest of the component
}
5. Using Third-Party Libraries: To simplify form creation and management in React, you can use third-party libraries like react-hook-form. This library provides hooks and components to help manage form state, handle form validation, and more.
import { useForm } from 'react-hook-form';
function LoginForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>Email</label>
<input type="email" {...register("email", { required: true, pattern: /^\S+@\S+$/i })} />
{errors.email && <p>Email is required and must be valid</p>}
<label>Password</label>
<input type="password" {...register("password", { required: true })} />
{errors.password && <p>Password is required</p>}
<button type="submit">Submit</button>
</form>
);
}