React Js check/uncheck all checkboxes with a button




Thanks for your feedback!
Your contributions will help us to improve service.
How to check/uncheck all checkboxes in React.js using a button?
The provided code is a React.js component that demonstrates how to implement a functionality to check or uncheck all checkboxes with the help of a button.
The component uses the useRef
hook from React to create a reference to an array that will store references to the checkbox elements. Two functions, uncheckAll
and checkAll
, are defined to iterate over the checkboxes and update their checked
property accordingly.
Each checkbox element is rendered using the input
tag within a label
tag. The ref
attribute is used to add the checkbox element to the checkboxesRef
array.
Finally, two buttons are provided: "Unchecked" and "Checked". When clicked, these buttons invoke the uncheckAll
and checkAll
functions, respectively, to update the state of the checkboxes.
Overall, this code demonstrates how to implement a check/uncheck all functionality for checkboxes in React.js.
React Js check/uncheck all checkboxes with a button Example
xxxxxxxxxx
<script type="text/babel">
const { useRef } = React;
function App() {
const checkboxesRef = useRef([]);
const checkboxValue = (e) => {
console.log(e.target.value);
};
const uncheckAll = () => {
checkboxesRef.current.forEach((checkbox) => {
checkbox.checked = false;
});
};
const checkAll = () => {
checkboxesRef.current.forEach((checkbox) => {
checkbox.checked = true;
});
};
return (
<div className='container'>
<h3>React Js check/uncheck all checkboxes with a button</h3>
<label>
<input ref={(element) => { checkboxesRef.current.push(element); }} value='Facebook' type='checkbox' onChange={checkboxValue} />
Facebook
</label>
<br />
<label>
<input ref={(element) => { checkboxesRef.current.push(element); }} value='Apple' type='checkbox' onChange={checkboxValue} />
Apple
</label>
<br />
<label>
<input ref={(element) => { checkboxesRef.current.push(element); }} value='Google' type='checkbox' onChange={checkboxValue} />
Google
</label>
<br />
<label>
<input ref={(element) => { checkboxesRef.current.push(element); }} value='Chatgpt' type='checkbox' onChange={checkboxValue} />
Chatgpt
</label>
<br />
<div className='buttonGroup'>
<button ClassName='uncheckAll' onClick={uncheckAll}>Unchecked</button>
<button className='checkAll' onClick={checkAll}>Checked</button>
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>