I have two reactive arrow function components stacked on top of each other (using absolute positioning), and they both have onClick properties. The problem is, I want to click the top one and both onClick functions fire. Is there a way to solve this problem?
This is a simplified version of the code:
const Card = ({...}) => { const styles = { optionsButton: { minWidth:0, minHeight: 0, padding: "2px", position: "absolute", color: "#808080", zIndex: 1, right: 5, top: 5, '&:hover':{ backgroundColor: 'rgb(0, 0, 0, 0.1)' } }, } const [hovering, setHovering] = useState(false) const [isCardExpanded, setIsCardExpanded] = useState(false) const expandCard = () => { setIsCardExpanded(true) } const closeCard = () => { setIsCardExpanded(false) } const mainPaperStyle = () => { let style = { padding: "10px", cursor: "pointer", position: "absolute", "&:hover": { filter: "brightness(97%)" } } //Extra code here modifying color of the style, no positioning modifications return style } const buttonAction = () => { console.log("Do action!") } return( <> <Paper sx={mainPaperStyle()} onClick={expandCard} onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)}> Lorem Ipsum {hovering && <Button variant="filled" id="card-button" sx={styles.optionsButton} onClick={() => buttonAction()}> <MoreVertIcon/> </Button> } </Paper> </> ) }
The screenshot below illustrates why I want to stack two components together:
I want a button to appear when the mouse is hovered over the top of the Paper component. The problem is that when I click the button, both expandCard
and buttonAction
fire. (BTW, I'm using Material UI)
You can use
$event.stopPropagation();
.So in your case you need to change the function
buttonAction
to thisand return clause
You can learn more here