Alvin Novian
Back to index

React handle click outside element

This approach can be used both in the Class component or Functional component, you need to change the code a bit for Functional component, it’s better to use alvin883/react-hooks streamich/react-use

class Navbar extends Component {
  setRef = (node) => {
    this.refWrapper = node;
  }

  handleClick = (event) => {
    // If the string is not inside the target,
    // then it's mean not related to this element anymore
    // and this thing should be closed
    if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
      this.handleClickOutside();
    }
  }

  handleClickOutside = () => {
    console.log('do something');
  }

  render() {
    return () {
      <div ref={setRef} style={{height: '200px', width: '200px'}}>
    }
  }
}