To check all checkboxes in a React component, you can use the .map()
method to loop over the checkbox elements and set the checked property to true.
Here is an example:
App.js
import React from "react";
export default class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
checkboxes: [
{ id: 1, label: "Checkbox 1", checked: false },
{ id: 2, label: "Checkbox 2", checked: false },
{ id: 3, label: "Checkbox 3", checked: false }
]
};
}
checkAll() {
const newCheckboxes = this.state.checkboxes.map((checkbox) => {
return { ...checkbox, checked: true };
});
this.setState({
checkboxes: newCheckboxes
});
}
unCheckAll() {
const newCheckboxes = this.state.checkboxes.map((checkbox) => {
return { ...checkbox, checked: false };
});
this.setState({
checkboxes: newCheckboxes
});
}
handleChange(checkboxId) {
let checkboxes = this.state.checkboxes;
for (let checkbox of checkboxes) {
if (checkbox.id == checkboxId) {
checkbox.checked = !checkbox.checked;
}
}
this.setState({ checkboxes: checkboxes });
}
render() {
return (
<div>
{this.state.checkboxes.map((checkbox) => (
<label key={checkbox.id}>
<input
type="checkbox"
checked={checkbox.checked}
onChange={() => this.handleChange(checkbox.id)}
/>
{checkbox.label}
</label>
))}
<button onClick={() => this.checkAll()}>Check all</button>
<button onClick={() => this.unCheckAll()}>UnCheck all</button>
</div>
);
}
}
In the code above, we have a MyComponent
class that contains a checkboxes
state variable. This variable holds an array of objects, each representing a checkbox. Each checkbox has an id
, a label
, and a checked
property that indicates whether the checkbox is checked or not.
In the render()
method, we loop over the checkboxes
array and render a checkbox for each item. Each checkbox has an onChange
event handler that calls a handleChange()
method to handle changes to the checkbox.
The component also has a checkAll()
method that is called when the user clicks the “Check all” button. This method uses the .map()
method to loop over the checkboxes array and create a new array of checkboxes with the checked
property set to true for each checkbox. It then uses the setState()
method to update the checkboxes state variable with the new array of checkboxes.
This will cause the component to re-render and show all checkboxes as checked.
Same like checkAll()
method we have create method unCheckAll()
method.
Output