notes/code/React Patterns

tagged: react, js, webdev

Detecting outside clicks

Stolen from this Medium article by Pitipat Srichairat.

class MyComponents extends React.Component {
componentDidMount = () => {
document.addEventListener('mousedown', this.handleClickOutside, false)
}
componentWillUnmount = () => {
document.removeEventListener('mousedown', this.handleClickOutside, false)
}
handleClickOutside = e => {
!this.container.contains(e.target) && console.log('Outside click detected!'))
}
render() {
return (
<div ref={e => this.container = e}>
{this.props.children}
</div>
)
}
}