I have a CardActionArea when I click on it redirects me to another page:
<Card>
<CardContent>
<CardActionArea component={RouterLink} to={`/poll/${poll.id}`} >
// My code
</CardActionArea>
</CardContent>
</Card>
I put a Button in the CardActionArea, when the Button is clicked it does an other action:
<Card>
<CardContent>
<CardActionArea component={RouterLink} to={`/poll/${poll.id}`} >
<Button onClick={props.myAction}>
{answer.text}
</Button>
</CardActionArea>
</CardContent>
</Card>
My problem is:
When I click on the Button, I also click on the CardActionArea.
I don't want to click on the CardActionArea, but just on the Button and call my myAction() without being redirected.
Someone help me ?
You need to call event.stopPropagation() in the Button's onClick and onMouseDown events in order to prevent those events from propagating to the CardActionArea. Stopping propagation of the click event is the most important aspect, but stopping propagation of the mouse-down event prevents the ripple effect from occurring on the CardActionArea (so the ripple only occurs on the Button).
Also if the CardActionArea component is overridden in such a manner as to make it an a tag, you may also need to call event.preventDefault() in the Button's click event to prevent the default browser behavior of navigating to the href specified by the a tag.
Here's a working example (based on one of the demos):
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardActionArea from "@material-ui/core/CardActionArea";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
const useStyles = makeStyles({
root: {
maxWidth: 345
},
media: {
height: 140
}
});
export default function MediaCard() {
const classes = useStyles();
return (
<Card className={classes.root}>
<CardActionArea
component="a"
href="https://material-ui.com"
onClick={() => console.log("CardActionArea clicked")}
>
<CardMedia
className={classes.media}
image="https://material-ui.com/static/images/cards/contemplative-reptile.jpg"
title="Contemplative Reptile"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="h2">
Lizard
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
Lizards are a widespread group of squamate reptiles, with over 6,000
species, ranging across all continents except Antarctica
</Typography>
<Button
size="small"
variant="contained"
color="primary"
onMouseDown={event => event.stopPropagation()}
onClick={event => {
event.stopPropagation();
event.preventDefault();
console.log("Button clicked");
}}
>
Learn More
</Button>
</CardContent>
</CardActionArea>
</Card>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With