The most straightforward way to deal with this is to have two separate handleClick
methods for the checkbox and the row (e.g. handleCheckboxClick
and handleRowClick
).
In handleCheckboxClick
you can then call event.stopPropagation();
in order to prevent handleRowClick
from being called.
So the following portions of EnhancedTable
would change from:
handleClick = (event, id) => {
if (event.target.classList.contains("selectCheckbox")) {
console.log("checkbox select");
} else {
console.log("row link");
}
const { selected } = this.state;
const selectedIndex = selected.indexOf(id);
let newSelected = [];
if (selectedIndex === -1) {
newSelected = newSelected.concat(selected, id);
} else if (selectedIndex === 0) {
newSelected = newSelected.concat(selected.slice(1));
} else if (selectedIndex === selected.length - 1) {
newSelected = newSelected.concat(selected.slice(0, -1));
} else if (selectedIndex > 0) {
newSelected = newSelected.concat(
selected.slice(0, selectedIndex),
selected.slice(selectedIndex + 1)
);
}
this.setState({ selected: newSelected });
};
...
<TableRow
hover
onClick={event => this.handleClick(event, n.id)}
role="checkbox"
aria-checked={isSelected}
tabIndex={-1}
key={n.id}
selected={isSelected}
>
<TableCell className="selectCheckbox" padding="checkbox">
<Checkbox
onClick={event => this.handleClick(event, n.id)}
className="selectCheckbox"
checked={isSelected}
/>
</TableCell>
to something like the following:
handleCheckboxClick = (event, id) => {
event.stopPropagation();
console.log("checkbox select");
const { selected } = this.state;
const selectedIndex = selected.indexOf(id);
let newSelected = [];
if (selectedIndex === -1) {
newSelected = newSelected.concat(selected, id);
} else if (selectedIndex === 0) {
newSelected = newSelected.concat(selected.slice(1));
} else if (selectedIndex === selected.length - 1) {
newSelected = newSelected.concat(selected.slice(0, -1));
} else if (selectedIndex > 0) {
newSelected = newSelected.concat(
selected.slice(0, selectedIndex),
selected.slice(selectedIndex + 1)
);
}
this.setState({ selected: newSelected });
};
handleRowClick = (event, id) => {
console.log("row link");
};
...
<TableRow
hover
onClick={event => this.handleRowClick(event, n.id)}
role="checkbox"
aria-checked={isSelected}
tabIndex={-1}
key={n.id}
selected={isSelected}
>
<TableCell className="selectCheckbox" padding="checkbox">
<Checkbox
onClick={event =>
this.handleCheckboxClick(event, n.id)
}
className="selectCheckbox"
checked={isSelected}
/>
Here's a CodeSandbox showing this approach:
