I have a Button
component (bootstrap-react
) that has a X
icon on one end of the button. Both the Button
and X
components have a onClick
handler defined.
However, when a user clicks on the X
icon, both the onClick
functions of both components are triggered. How do we ensure that only the X
icon's onClick
is triggered when the icon is clicked?
import { Button } from 'react-bootstrap';
import { X } from 'react-bootstrap-icons';
function MyButton({onClick}) {
const handleRemoveClick = () => {
console.log('Clicked on icon')
}
return (
<Button variant="light" onClick={onClick}>
<span className="btn-text">Hello</span>
<X fill="#aaa" onClick={handleRemoveClick} />
</Button>
)
}
You can invoke stopPropagation on the event object when the X
button is clicked so that the event stops propagating.
const handleRemoveClick = (e) => {
e.stopPropagation();
console.log('Clicked on icon')
}