What Is Checkbox?
Checkbox are small square buttons that allow uses to select multiple options from a list. Checkbox commonly used for:
- Select Multiple Products like color, size, brand.
- Choosing For Categories like sports, music, tech.
- Turn On or Off Any Features like dark mode, notifications.
How Checkbox Feature Work In React?
Single Checkbox in React
When we use a single checkbox, we connect with useState hook. this state holds true (checked) or false (unchecked). when the user click on the checkbox, so react updates the state and the UI changes automatically.
Example logic:
Imagine a form asking you, “Do you agree to terms?” You can select or deselect it. react work this selctions using useState.
Multiple Checkboxes in React
Now, what for you want to allow the user to choose more than one option (like multiple checkbox selection)?
For example:
In this case, we manage checkboxes using object or array in the state, where each checkbox has its own value (true or false). when a user clicks a checkbox, so react updates only that specific item in the state.
Further we will understand real life example in code:
Single Checkbox in React
We use single checkbox for accept any agreement or etc. we use useState() function to manage the checkbox is checked or not.
When the user click the checkbox, it updates the state using setState and reflect the result in UI.
import React, { useState } from 'react';
function ConsentBox() {
const [agreed, setAgreed] = useState(false);
const handleConsent = (e) => {
setAgreed(e.target.checked);
};
return (
<div>
<h2>Agreement Confirmation</h2>
<label>
<input
type="checkbox"
checked={agreed}
onChange={handleConsent}
/>
I accept the user policy
</label>
<p>Status: {agreed ? 'Accepted ✅' : 'Not Accepted ❌'}</p>
</div>
);
}
export default ConsentBox;
Explanation of Code:
Code Part | Explanation |
---|---|
useState(false) | Start with unchecked checkbox |
handleConsent | Update (agreed) when checkbox is clicked |
checked={agreed} | Syncs checkbox value with state |
Status: | Shows real-time result when user clicks |
Dynamic Multiple Checkbox in React
We put all the checkbox options in array without writing each checkbox manually.
Instead of writing each checkbox manually, we keep all the options in a list (array).
const hobbies = ['Singing', 'Coding', 'Painting'];
Selected Items in Another Array:
When a user checks something, we save their selected items in another array using React useState().
const [selectedHobbies, setSelectedHobbies] = useState([]);
Dynamic:
“Dynamic” means, we don’t repeat the same code again and again for each checkbox.
- We use .map() to automatically create all checkboxes.
- This makes the code short, clean and easy to update.
import React, { useState } from 'react';
function SkillSelector() {
const skills = ['Coding', 'Design', 'Testing', 'Debugging'];
const [chosenSkills, setChosenSkills] = useState([]);
const updateSkill = (skill) => {
if (chosenSkills.includes(skill)) {
setChosenSkills(chosenSkills.filter((s) => s !== skill));
} else {
setChosenSkills([...chosenSkills, skill]);
}
};
return (
<div>
<h2>Select Your Skills</h2>
{skills.map((skill) => (
<label key={skill} style={{ display: 'block', marginBottom: '6px' }}>
<input
type="checkbox"
checked={chosenSkills.includes(skill)}
onChange={() => updateSkill(skill)}
/>
{skill}
</label>
))}
<div style={{ marginTop: '15px' }}>
<strong>Selected Skills:</strong>{' '}
{chosenSkills.length ? chosenSkills.join(', ') : 'None'}
</div>
</div>
);
}
export default SkillSelector;
Explanation:
Key Code Part | Explanation |
---|---|
skills | All available options (array) |
chosenSkills | User selected items (array) |
updateSkill() | Toggles skill on checkbox click |
checked={} | Make checkbox reflect if selected |
map() | Dynamically generates all checkboxes |
Toggle Functionality In Checkbox
Sometime we select “Select All” button for all check all the checkboxes. this feature add provide for select all box in single click when you want to checks all items.
// function to mark all choices as selected
const markEvery = () => {
const allChosen = Object.fromEntries(choices.map(item => [item, true]));
updateSelected(allChosen);
};
// function to unmark all selected choices
const unmarkEvery = () => {
const noneChosen = Object.fromEntries(choices.map(item => [item, false]));
updateSelected(noneChosen);
};
With these functions, you can add buttons in the JSX:
<button onClick={markEvery}>Select All</button>
<button onClick={unmarkEvery}>Deselect All</button>
Complete Component with All/None Toggle
Here the full version of code has ability to select or deselect all checkboxes:
import React, { useState } from 'react';
function SkillSelector() {
const [languageState, updateLanguageState] = useState({
HTML: false,
CSS: false,
React: false,
Node: false,
GoLang: false,
});
const skillList = Object.keys(languageState);
const handleToggle = (e) => {
const { name, checked } = e.target;
updateLanguageState({
...languageState,
[name]: checked,
});
};
const markAllSkills = () => {
const marked = Object.fromEntries(skillList.map(skill => [skill, true]));
updateLanguageState(marked);
};
const unmarkAllSkills = () => {
const cleared = Object.fromEntries(skillList.map(skill => [skill, false]));
updateLanguageState(cleared);
};
return (
<div>
<h2>Pick Your Tech Skills:</h2>
<button onClick={markAllSkills}>Mark All</button>
<button onClick={unmarkAllSkills}>Unmark All</button>
<div style={{ marginTop: '10px' }}>
{skillList.map((skill) => (
<label key={skill} style={{ display: 'block' }}>
<input
type="checkbox"
name={skill}
checked={languageState[skill]}
onChange={handleToggle}
/>
{skill}
</label>
))}
</div>
<div style={{ marginTop: '20px' }}>
<h3>Your Selected Skills:</h3>
<ul>
{skillList
.filter((skill) => languageState[skill])
.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
</div>
</div>
);
}
export default SkillSelector;
Example Use Cases
- Product Filters: Multiple checkboxes are used in e-commerce applications to filter products by categories, brands, sizes or colors.
- Survey or Quiz Forms: Forms are require by users to select more than one options (multiple options).
- Data Tables with Bulk Actions: Checkboxes allow users to select multiple rows and apply bulk actions, such as delete or move items in data tables.