Detect a click outside of a React Component

August 31 2016

Here's some code to detect when you click outside of a react component. This is useful if you have a modal window component and you want to detect a click outside of the modal to dismiss it.

componentDidMount() {
    document.addEventListener('click', this.handleClickOutside.bind(this), true);

componentWillUnmount() {
    document.removeEventListener('click', this.handleClickOutside.bind(this), true);

handleClickOutside(event) {
    const domNode = ReactDOM.findDOMNode(this);

    if ((!domNode || !domNode.contains( {
            visible : false