I have set the onClick
prop on my div which will navigate to a new page when clicked. svg
is absolutely positioned. How do I avoid the click event on the svg
element?
I've already tried stopPropagation()
but it doesn't work.
<div
className={classes.container}
onClick={() => navigate(`${props.productName}`)}
>
<img src={props.image} alt="" />
<svg></svg>
</div>
CodePudding user response:
Well the obvious answer would be to put it outside of the div
.
But if you really can't, you can always use CSS for this.
Try using pointer-events
Example:
HTML -
<div
className={classes.container}
onClick={() => navigate(`${props.productName}`)}
>
<img src={props.image} alt="" />
<svg className='no-events'></svg>
</div>
CSS -
.no-events {
pointer-events: none;
}
CodePudding user response:
Check to see if e.target === e.currentTarget
.
function Example() {
function handleClick(e) {
if (e.target === e.currentTarget) {
console.log('Only container clicked');
}
}
return (
<div
className="container"
onClick={handleClick}
>
<button>Click me!</button>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
#react { padding: 0; border: 0; margin: 0;}
.container { border: 5px solid white; padding: 1em; background-color: lightblue; }
div:hover { border: 5px solid cornflowerblue; }
div:hover, button:hover { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
CodePudding user response:
You can achieve by doing these.
- Check for the target element tag when event is triggered.
- Assign Id's to the elements and execute your code based on the Id.
- Use CSS pointer-events to disable pointer events of that element.