In React, is it possible to disable a redirection when a switch button is placed inside a redirection component?
I have a clickable TableRow which redirects to another component and a switch button (checkbox) inside, like this:
The TableRow
component with his TableCell
and the Switch
button inside:
<TableRow
className="h-40 cursor-pointer"
hover
role="checkbox"
aria-checked={isSelected}
tabIndex={-1}
key={n.id}
selected={isSelected}
onClick={event => handleClick(n)}
>
<TableCell component="th" scope="row" align="left">
<Switch
checked={state.checkedB}
onChange={handleChange("checkedB")}
value="checkedB"
/>
</TableCell>
</TableRow>
Here is the handleChange
function and the state of the Switch button:
const [state, setState] = React.useState({
checkedB: true,
});
const handleChange = name => event => {
setState({ ...state, [name]: event.target.checked });
};
And here is the handleClick
function in the TableRow
component which redirect to another component:
function handleClick(item){
props.history.push('/apps/fournisseurs/'+item.id+'/'+ item.handle);
}
You'll want to stop propagation ( event.stopPropagation()
) when you click on the Switch
. This will stop the event from bubbling up the chain and will essentially "ignore" the parent click handler ( onClick
in this case).
const handleChange = name => event => {
event.stopPropagation();
setState({ ...state, [name]: event.target.checked });
};
<TableRow
className="h-40 cursor-pointer"
hover
role="checkbox"
aria-checked={isSelected}
tabIndex={-1}
key={n.id}
selected={isSelected}
onClick={event => handleClick(n)}
>
<TableCell component="th" scope="row" align="left">
<Switch
checked={state.checkedB}
onChange={handleChange("checkedB")}
value="checkedB"
onClick={e => e.stopPropagation()}
/>
</TableCell>
</TableRow>
Edit:
After finding another answer , unfortunately the way for the above code to work would be to add an additional handler to the Switch
component of onClick={e => e.stopPropagation()}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.