I’m working in React and using MUI components. The problem I’m running into is that when I click the subscribe Button, the click event for the CardActionArea component is running as well. I understand that this is because of propagation/bubbling, but I can’t figure out how to fix it from what I’ve found online. I’m hoping someone here can help me with a solution.
function subscribeClick(event) {
event.stopPropagation();
console.log("button was clicked");
}
function cardClick() {
console.log("card was clicked");
}
Above is the code for the functions
return (
<Card variant="outlined" className="card-item" sx={{ width: 500, verticalAlign: 'top' }} style={{ display: 'inline-block', borderRadius: '0', verticalAlign: 'top' }}>
<CardActionArea component={RouterLink} to={'./Details/' + props.reportName} onClick={cardClick}>
<CardContent className='card-content' style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<h2 style={{ display: "inline-block" }} className='card-header'>{props.reportName}</h2>
<Button onClick={subscribeClick} variant="contained">Subscribe</Button>
</CardContent>
</CardActionArea>
<CardActions style={{ justifyContent: 'space-around' }}>
{StatusBars}
</CardActions>
</Card>
);
There is the code for the components that call those functions.
I have tried passing in the event to the subscribeClick function in the onClick of the button by using an arrow function, I’ve tried calling subscribeClick using this.subscribeClick, as well as various different ways of calling the function from Buttons onClick. I can’t figure out why it is still bubbling up to the cardClick function.
2
Answers
The problem here is not the
CardActionArea
component or your functions that you have implemented.The problem is with the
Link
component.When you click on a
Link
component, and by extension what’s inside it as well, it will simply redirect you to the page.Calling
event.stopPropagation()
here only stops the propagation of theonClick
event, but does not stop the default behaviour of theLink
component.What you’re missing here is
event.preventDefault()
inside of your button function, which prevents the default behaviour of theLink
component.If you also wish to disable the ripple effect of the
CardActionArea
component when clicking on "Subscribe", you should add the following to your button:also if you want to disable the ripple effect when click on the subscribe button you can do something like this: