Articles in this section
Category / Section

How can I get the value of a react checkbox if it has been checked?

2 mins read

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

  1. 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 },
      ];
  };
  1. 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)}
       />
   ))}
  1. 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(', ');
}
  1. 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:

image.png

Additional References

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied