How to show value of checkbox on react

Viewed 45

I have a checkbox filters. The problem is that I need to display all checked checkbox label (e.g. if clicked Vimeo there should be a <h1> with Vimeo filter applied).

const checkboxTarget = ['Dailymotion', 'Vimeo', 'VK']

{checkboxTarget.map((text, index) => (
  <div>
    <input type="checkbox" id="flexCheckIndeterminate" />
    <label style={{ marginLeft: '5px' }} class="form-check-label" for="flexCheckIndeterminate">
      {text}
    </label>
  </div>
))}
1 Answers

In a functional component,

const[selectedCheckbox, setSelectedCheckbox] = useState("");

And then, add an OnClick Listener to the checkbox. Don't forget to check if the checkbox is checked. I would write a function to update SelectedCheckbox if multiple selection is a possibility.

<input type="checkbox" value={text} id="flexCheckIndeterminate" onClick={(e) => {if(e.target.checked){setSelectedCheckbox(e.target.value)} }} />
Related