Welcome to Part 7 of the React for Beginners series!
You've already seen how to manage state and side effects — now it’s time to handle user input and form elements in React.
Whether you're building a login page, a search bar, or a feedback form, you'll need to handle form data the React way: with controlled components.
✍️ What Is a Controlled Component?
In React, a form element is controlled when:
- Its value is stored in state
- Changes are handled by an
onChange
function
This gives React full control over form data, making validation and updates easy.
🧪 Example: Basic Text Input
import { useState } from 'react';
function NameForm() {
const [name, setName] = useState('');
function handleChange(e) {
setName(e.target.value);
}
return (
<div>
<input type="text" value={name} onChange={handleChange} />
<p>Hello, {name || 'stranger'}!</p>
</div>
);
}
✅ The input
’s value is tied to React state. As you type, state updates, and React re-renders the result.
📨 Handling Form Submission
You’ll often want to do something when the user submits a form.
function EmailForm() {
const [email, setEmail] = useState('');
function handleSubmit(e) {
e.preventDefault(); // Prevent page refresh
alert(`Submitted: ${email}`);
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<button type="submit">Submit</button>
</form>
);
}
🧮 Handling Multiple Fields
You can use one state object to track multiple fields:
function LoginForm() {
const [form, setForm] = useState({ username: '', password: '' });
function handleChange(e) {
setForm({
...form,
[e.target.name]: e.target.value,
});
}
return (
<form>
<input
name="username"
value={form.username}
onChange={handleChange}
placeholder="Username"
/>
<input
name="password"
type="password"
value={form.password}
onChange={handleChange}
placeholder="Password"
/>
</form>
);
}
🧠 The key part here: e.target.name
dynamically updates the corresponding field in the object.
✅ Controlled vs Uncontrolled Components
Controlled | Uncontrolled |
---|---|
Value is managed via useState
|
Value is stored in the DOM |
You read/update input via React state | You read input using ref
|
Preferred for most React applications | Useful in rare cases or for quick forms |
🧩 Bonus: Simple Validation
You can add inline validation like this:
{email && !email.includes('@') && <p style={{ color: 'red' }}>Invalid email</p>}
Or use HTML
built-in validation with required
, minLength
, etc.
✍️ Challenge for You
Create a ContactForm
component:
- Fields: name, email, message
- Show a thank-you message on submit
- Validate that all fields are filled
✅ Summary
- Use
useState
to control form fields. - Tie
value
andonChange
to React state. - Use
onSubmit
to handle form submissions. - Track multiple fields with one state object if needed.
🔜 What’s Next?
In Part 8, we’ll look at how to structure your React projects, organize components, and separate concerns in larger apps.
You’ve just learned one of the most practical React skills — forms are everywhere! 🧾
Top comments (0)