Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent checkbox and clickable table row conflict

I have a clickable table row and checkbox in that row. When user click on that row, user will be redirected to other page. That was expected behavior. Now the problem is when user click on checkbox, user also will be redirected to other page. This is not the expected behavior. Clicking on checkbox should not trigger redirect() method

  handleChange(e) {
    this.setState({
      checkbox: e.target.checked,
    });
  }

  redirect() {
    Router.push('/registration/register/RegisterEditor', '/verification/e7fe5b68-94e8-435f-8303-5308fd1f7e69');
  }

              <tbody>
                {inventory.list().map((data, index) => (
                  <tr key={'asset'.concat(index)} onClick={() => { this.redirect(); }} tabIndex={index + 1} role="button">
                    <td className="text-center">{index + 1}</td>
                    <td>{data.item}</td>
                    <td width="3%">
                      <Input className="mx-auto" type="checkbox" onChange={this.handleChange} />
                    </td>
                  </tr>
                ))}
              </tbody>

Output:

enter image description here

How can I solve this problem? Thanks in advance.

like image 320
sg552 Avatar asked Dec 06 '25 08:12

sg552


1 Answers

Have a look at this snippet: https://codesandbox.io/s/qx6Z1Yrlk

You have two options:

Adding an if-statement in your redirect function checking what element has been clicked on and only redirect if it's the row (make sure you pass in the event).

Or, listening for a click event on the checkbox as well, passing in the event, and stop the event from bubbling to the row element. stopPropagation won't work in the change event listener as the click event is fired before the change event.

like image 90
Meldon Avatar answered Dec 08 '25 22:12

Meldon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!