REACT
React Form: Syntax, Usage, and Examples
A React form allows users to input and submit data while React handles state updates efficiently. Forms in React work similarly to regular HTML forms but require controlled components for handling user input.
How to Use a React Form
A React form consists of input fields, event handlers, and a submission function. Controlled components ensure React manages the form’s state.
Creating a Basic React Form
This example shows a simple React form with a controlled input field and a submit button.
import { useState } from "react";
function SimpleForm() {
const [name, setName] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
alert(`Hello, ${name}!`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
Here, useState
stores the input value, and onChange
updates the state when the user types. The handleSubmit
function prevents the default form submission and displays an alert with the entered name.
When to Use a React Form
Forms in React are essential for collecting and handling user input. They are widely used in web applications for various purposes.
Handling User Authentication
Forms allow users to log in or register by entering their credentials.
function LoginForm() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
console.log("Logging in with:", email, password);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" placeholder="Email" onChange={(e) => setEmail(e.target.value)} />
<input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Login</button>
</form>
);
}
Handling Search Functionality
A form can capture user search input and trigger a search query.
function SearchBar({ onSearch }) {
const [query, setQuery] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
onSearch(query);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Search..." onChange={(e) => setQuery(e.target.value)} />
<button type="submit">Search</button>
</form>
);
}
Validating User Input
React forms can validate inputs before submission to prevent errors.
function EmailForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
if (!email.includes("@")) {
setError("Invalid email address");
return;
}
console.log("Valid email submitted:", email);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" placeholder="Enter your email" onChange={(e) => setEmail(e.target.value)} />
{error && <p style={{ color: "red" }}>{error}</p>}
<button type="submit">Submit</button>
</form>
);
}
Examples of React Forms
How to Get Selected Elements from a React Form
You can use the useRef
hook to access selected form elements without relying on state.
import { useRef } from "react";
function SelectExample() {
const selectRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
alert(`Selected value: ${selectRef.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<select ref={selectRef}>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
<button type="submit">Submit</button>
</form>
);
}
This example shows how to get the selected value from a dropdown using a reference.
Using React Form Hook
react-hook-form
simplifies form handling and validation with minimal re-renders.
import { useForm } from "react-hook-form";
function HookFormExample() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("username", { required: true })} placeholder="Username" />
{errors.username && <p style={{ color: "red" }}>Username is required</p>}
<button type="submit">Submit</button>
</form>
);
}
React Form Validation
Client-side validation ensures data accuracy before submission.
function ValidationForm() {
const [input, setInput] = useState("");
const [error, setError] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
if (input.length < 3) {
setError("Input must be at least 3 characters long");
return;
}
console.log("Valid input:", input);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" onChange={(e) => setInput(e.target.value)} />
{error && <p style={{ color: "red" }}>{error}</p>}
<button type="submit">Submit</button>
</form>
);
}
Learn More About React Forms
Do You Need Form Libraries in React?
React allows you to build forms with just state and event handlers. However, form libraries like react-hook-form
and Formik
simplify state management and validation.
import { useFormik } from "formik";
import * as Yup from "yup";
function FormikExample() {
const formik = useFormik({
initialValues: { email: "" },
validationSchema: Yup.object({
email: Yup.string().email("Invalid email").required("Required"),
}),
onSubmit: (values) => console.log(values),
});
return (
<form onSubmit={formik.handleSubmit}>
<input
type="email"
name="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
{formik.errors.email && <p style={{ color: "red" }}>{formik.errors.email}</p>}
<button type="submit">Submit</button>
</form>
);
}
React Form Example with Multiple Inputs
Handling multiple input fields requires maintaining state for each field.
function MultiInputForm() {
const [formData, setFormData] = useState({ name: "", email: "" });
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" onChange={handleChange} placeholder="Name" />
<input type="email" name="email" onChange={handleChange} placeholder="Email" />
<button type="submit">Submit</button>
</form>
);
}
React forms provide flexibility, allowing controlled and uncontrolled components, client-side validation, and easy data management. Choosing between native state handling and libraries depends on the complexity of the form and project requirements.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.