I have a component called Dialog
, in which I attach an event listener on mouse clicks on the window
object.
componentDidMount() {
document.addEventListener('click', this.handleClick);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick);
}
How can I detect (in the handleClick
function) whether a click has been fired inside the component or outside? Note that this dialog contains different elements and child components.
To determine whether the click position is inside or outside our component, combine window. onclick with the useEffect() hook as follows: useEffect(() => { window. onclick = (event) => { if (event.
To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.
Detecting an outside click of a functional component Let's build an HTML tooltip by creating a React functional component named InfoBox . The tooltip will appear when the user clicks a button, and it will be closed if the user clicks outside of the tooltip component.
parent.contains(child)
is your friend. This solution using refs
might not be perfect, but simply using this
does not work as it's not a proper DOM node. I'm using React 15 here, so keep in mind that in earlier versions you'd have to use .getDOMNode()
on the parent.
class Dialog extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
document.addEventListener('click', this.handleClick);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick);
}
handleClick(e) {
if (this.node.contains(e.target)) {
console.log('You clicked INSIDE the component.')
} else {
console.log('You clicked OUTSIDE the component.')
}
}
render() {
return(
<span ref={node => this.node = node}>
Level 0<br/>
<span>
Level 1.<br/>
<span>Level 2.</span>
</span>
</span>
);
}
}
ReactDOM.render(<Dialog/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>
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