How can I get the value of a react checkbox if it has been checked?
In this article, we will demonstrate the process of displaying the checked value of a checkbox component. This can be accomplished by utilizing a change event associated with the checkbox. The code snippet provided below illustrates the steps necessary to achieve this functionality.
Step-by-Step Implementation
-
Create the Checkbox Component
Define a functional component named
CheckBox
that will render a list of checkboxes and display the selected values.
const CheckBox = () => {
let checkboxes = [
{ id: 1, label: 'banana', isChecked: false },
{ id: 2, label: 'apple', isChecked: false },
{ id: 3, label: 'orange', isChecked: false },
];
};
-
Render the Checkboxes
Use the
map
function to render each checkbox and pass the necessary props.
{checkboxes.map((checkbox) => (
<CheckBoxComponent
key={checkbox.id}
label={checkbox.label}
checked={checkbox.isChecked}
onChange={() => handleCheckboxChange(checkbox.id)}
/>
))}
-
Handle State and Selection
Implement a function to handle checkbox state changes and update the selected values.
const handleCheckboxChange = (checkboxId) => {
const updatedCheckboxes = checkboxes.map((checkbox) =>
checkbox.id === checkboxId
? { ...checkbox, isChecked: !checkbox.isChecked }
: checkbox
);
checkboxes = updatedCheckboxes;
selectedValues = checkboxes
.filter((checkbox) => checkbox.isChecked)
.map((checkbox) => checkbox.label);
document.getElementById('result').innerHTML = ' Selected Values: ' + selectedValues.join(', ');
}
-
Display Selected Values
Show the selected values in a div element below the checkboxes.
<div id='result' style={{marginTop: 20 + 'px'}}>
Selected Values: {selectedValues.join(', ')}
</div>
Conclusion
The CheckBox
component is a versatile element that can be used in forms and settings where multiple selections are required. By following the steps above, you can implement a checkbox component that is both functional and user-friendly.
Demo Sample Link: Get Checkbox value
Output:
Additional References
- React Official Documentation: https://reactjs.org/docs/getting-started.html
- Syncfusion React UI Components: https://www.syncfusion.com/react-ui-components
- Node.js: https://nodejs.org/
- npm: https://www.npmjs.com/