DragoJokera
DragoJokera

Reputation: 1035

How could I stop execution of onClick event for a specific element in React

I am using Material UI and I have a TableRow element, which has onClick event. But now I have to add a checkbox inside the table. The checkbox is wrapped in TableCell element, which is part of the TableRow. Now when I click on the checkbox it is triggering the onClick event, which I do not want to happen. Is it possible somehow to stop the propagation of the function !? Could I disable onClick for that specific cell and if yes, will it be possible to click on the checkbox? Or I should do some magic trick inside the function call if the element is with some specific ID for example not to be executed?

Upvotes: 1

Views: 918

Answers (1)

veeKINGPIN
veeKINGPIN

Reputation: 105

You can use e.stopPropagation() in the checkbox click handler so that the parent element's click event is not fired.

function MyCheckbox() {
  function handleClick(e) {
    e.stopPropagation();
    ....
  }

  return (
    <label>
      <input type="checkbox" onClick={handleClick} />
      Click me
    </label>
  );
}

Upvotes: 2

Related Questions