You need to handle user input, manage form state, and handle submission—usually in a controlled way.
Steps:
1. Controlled Components Approach (Most Common)
Create State for Each Input
React uses state to track input values, making the component the "single source of truth".
import { useState } from 'react';
function MyForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
function handleSubmit(e) {
e.preventDefault(); // Prevents page reload
alert(`Name: ${name}, Email: ${email}`);
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
/>
<button type="submit">Submit</button>
</form>
);
}