Checkboxes and Radio Buttons in React
Learn how to handle checkboxes and radio buttons in React using state, event handlers, and controlled form components.
1. Introduction to Checkboxes and Radio Buttons
Checkboxes and radio buttons are form elements used to collect choices from users. A checkbox allows users to select or deselect an option. Radio buttons allow users to select one option from a group.
In React, we can manage these selections using state. The checked prop determines whether an option is selected, and the onChange handler updates the state.
checked to control the selected state
of a checkbox or radio button. Use onChange
to respond to changes.
2. Understanding the Difference
| Feature | Checkbox | Radio Button |
|---|---|---|
| Purpose | Select or deselect an option. | Select one option from a group. |
| Multiple selections | Multiple options can be selected. | Only one option in the same group can be selected. |
| React prop | checked |
checked |
| Common use | Accepting terms or selecting interests. | Selecting a course or payment method. |
3. Creating a Controlled Checkbox
A controlled checkbox uses React state to store whether the checkbox is selected. The event.target.checked property gives the current checked value.
Example
import { useState } from "react";
function TermsCheckbox() {
const [accepted, setAccepted] = useState(false);
function handleChange(event) {
setAccepted(event.target.checked);
}
return (
<div>
<label>
<input
type="checkbox"
checked={accepted}
onChange={handleChange}
/>
I accept the terms and conditions
</label>
<p>
Accepted: {accepted ? "Yes" : "No"}
</p>
</div>
);
}
export default TermsCheckbox;
Expected Output
Accepted: No
Initially, the checkbox is unchecked because accepted is false. When the user selects it, the state becomes true and the displayed message changes to Yes.
4. Selecting Multiple Options with Checkboxes
Sometimes users need to select more than one option. We can store the selected options in an array and update that array when a checkbox changes.
Example: Course Interests
import { useState } from "react";
function CourseInterests() {
const [courses, setCourses] = useState([]);
function handleChange(event) {
const { value, checked } = event.target;
if (checked) {
setCourses((previousCourses) => [
...previousCourses,
value
]);
} else {
setCourses((previousCourses) =>
previousCourses.filter(
(course) => course !== value
)
);
}
}
return (
<div>
<h3>Select Course Interests</h3>
<label>
<input
type="checkbox"
value="React"
checked={courses.includes("React")}
onChange={handleChange}
/>
React
</label>
<label>
<input
type="checkbox"
value="Angular"
checked={courses.includes("Angular")}
onChange={handleChange}
/>
Angular
</label>
<label>
<input
type="checkbox"
value="Python"
checked={courses.includes("Python")}
onChange={handleChange}
/>
Python
</label>
<p>Selected Courses: {courses.join(", ")}</p>
</div>
);
}
export default CourseInterests;
Expected Output
Select Course Interests
Selected Courses: React, Angular
The courses array stores selected values. When a user checks an option, its value is added. When an option is unchecked, filter() removes that value from the array.
5. Creating Radio Buttons
Radio buttons are used when a user must select one option from a group. Give related radio buttons the same name attribute and manage the selected value using state.
Example: Preferred Batch
import { useState } from "react";
function BatchSelection() {
const [batch, setBatch] = useState("Morning");
return (
<div>
<h3>Choose Your Preferred Batch</h3>
<label>
<input
type="radio"
name="batch"
value="Morning"
checked={batch === "Morning"}
onChange={(event) =>
setBatch(event.target.value)
}
/>
Morning
</label>
<label>
<input
type="radio"
name="batch"
value="Evening"
checked={batch === "Evening"}
onChange={(event) =>
setBatch(event.target.value)
}
/>
Evening
</label>
<p>Selected Batch: {batch}</p>
</div>
);
}
export default BatchSelection;
Expected Output
Choose Your Preferred Batch
Selected Batch: Morning
The batch state stores the selected option. Choosing Evening updates the state to Evening, and React displays the new selection.
6. CIIT Training Institute Course Registration Example
Consider a student named Samadhan Samiksha who wants to register for a course at CIIT Training Institute. The form below demonstrates how a checkbox and radio buttons can be used together.
Example
import { useState } from "react";
function CIITRegistration() {
const [studentName, setStudentName] =
useState("Samadhan Samiksha");
const [course, setCourse] = useState("React");
const [termsAccepted, setTermsAccepted] =
useState(false);
function handleSubmit(event) {
event.preventDefault();
console.log({
studentName,
course,
termsAccepted
});
}
return (
<form onSubmit={handleSubmit}>
<h2>CIIT Training Institute</h2>
<label htmlFor="studentName">
Student Name:
</label>
<input
id="studentName"
value={studentName}
onChange={(event) =>
setStudentName(event.target.value)
}
/>
<p>Select a Course:</p>
<label>
<input
type="radio"
name="course"
value="React"
checked={course === "React"}
onChange={(event) =>
setCourse(event.target.value)
}
/>
React
</label>
<label>
<input
type="radio"
name="course"
value="Angular"
checked={course === "Angular"}
onChange={(event) =>
setCourse(event.target.value)
}
/>
Angular
</label>
<label>
<input
type="checkbox"
checked={termsAccepted}
onChange={(event) =>
setTermsAccepted(event.target.checked)
}
/>
I confirm my registration details.
</label>
<button type="submit">
Submit Registration
</button>
</form>
);
}
export default CIITRegistration;
Expected Console Output
{
studentName: "Samadhan Samiksha",
course: "React",
termsAccepted: false
}
This example stores the student name, selected course, and checkbox status in React state. Submitting the form logs the current values to the console. It demonstrates form handling only and does not save registration data to a database.
7. Handling Checkbox and Radio Button Events
For checkboxes, use event.target.checked to read whether the option is selected. For radio buttons, use event.target.value to read the selected option.
Checkbox Handler
function handleCheckboxChange(event) {
setAccepted(event.target.checked);
}
Radio Button Handler
function handleRadioChange(event) {
setCourse(event.target.value);
}
| Property | Meaning | Common use |
|---|---|---|
event.target.checked |
Returns true or false. | Checkbox selection |
event.target.value |
Returns the selected value. | Radio button selection |
8. Common Mistakes
Mistake 1: Using checked Without Updating State
<input
type="checkbox"
checked={accepted}
/>
The checkbox is controlled by accepted, but no handler updates that state when the user interacts with it.
Correct Code
<input
type="checkbox"
checked={accepted}
onChange={(event) =>
setAccepted(event.target.checked)
}
/>
Mistake 2: Using Different Names for One Radio Group
<input type="radio" name="morning" value="Morning" />
<input type="radio" name="evening" value="Evening" />
Different name attributes create separate radio groups, so the browser may allow both options to be selected.
Correct Code
<input type="radio" name="batch" value="Morning" />
<input type="radio" name="batch" value="Evening" />
Mistake 3: Reading the Wrong Event Property
setAccepted(event.target.value);
A checkbox's selected status is represented by its checked property, not its value property.
Correct Code
setAccepted(event.target.checked);
9. Practice Tasks
Complete these tasks to practise checkboxes and radio buttons.
Summary
Checkboxes and radio buttons collect selections from users in React forms. A checkbox can be selected or deselected, and multiple checkboxes can be managed using an array in state. Radio buttons with the same name allow the user to choose one option from a group. The checked prop controls selection, event.target.checked reads checkbox status, and event.target.value reads the selected radio option. These techniques can be used to build course registration forms and other interactive form interfaces at CIIT Training Institute.