React On Click Outside HOC

6.13.2 · maintenance · verified Sun Apr 19

react-onclickoutside is a Higher Order Component (HOC) for React class components, currently at version 6.13.2. It enables wrapped components to detect and respond to click events that occur anywhere in the document outside their own DOM element, commonly used for dismissing menus, modals, or dropdowns. While it supports React versions 15.5.x through 18.x, the library's documentation explicitly recommends against its use with modern React functional components and hooks, suggesting manual implementation of `useRef` and `useEffect` instead. The project indicates it requires community support for continued maintenance. It relies on the `.classList` property, necessitating a polyfill like `dom4` for compatibility with older browsers like Internet Explorer. Releases are irregular, with the last major refactor to ES6 classes occurring in v6.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `onClickOutside` HOC with an ES6 class component to create a dropdown menu that closes when a user clicks anywhere outside of it. The `handleClickOutside` method is a mandatory implementation for components wrapped by this HOC.

import React, { Component } from 'react';
import onClickOutside from 'react-onclickoutside';

class DropdownMenu extends Component {
  constructor(props) {
    super(props);
    this.state = { isOpen: false };
    this.toggleMenu = this.toggleMenu.bind(this);
  }

  toggleMenu() {
    this.setState(prevState => ({ isOpen: !prevState.isOpen }));
  }

  // This method is required by react-onclickoutside HOC
  handleClickOutside = (evt) => {
    // console.log('Clicked outside!', evt.target);
    if (this.state.isOpen) {
      this.setState({ isOpen: false });
    }
  };

  render() {
    return (
      <div style={{ position: 'relative', display: 'inline-block' }}>
        <button onClick={this.toggleMenu}>Toggle Dropdown</button>
        {this.state.isOpen && (
          <div
            style={{
              position: 'absolute',
              backgroundColor: '#f9f9f9',
              minWidth: '160px',
              boxShadow: '0px 8px 16px 0px rgba(0,0,0,0.2)',
              zIndex: 1,
              padding: '12px 16px',
              marginTop: '5px'
            }}
          >
            <a href="#" style={{ display: 'block', textDecoration: 'none', color: 'black' }}>Link 1</a>
            <a href="#" style={{ display: 'block', textDecoration: 'none', color: 'black' }}>Link 2</a>
            <a href="#" style={{ display: 'block', textDecoration: 'none', color: 'black' }}>Link 3</a>
          </div>
        )}
      </div>
    );
  }
}

export default onClickOutside(DropdownMenu);

view raw JSON →