react-onclickoutside

repository·master·Indexed 23 days ago

https://github.com/pomax/react-onclickoutside

A React Higher Order Component (HOC) that allows components to detect and respond to click events occurring outside of their own DOM boundaries. It supports custom event types, scrollbar exclusion, and specific CSS classes to ignore certain elements. Version 6.13.2 is designed for React Class Components; for React v16+ functional components, the use of useEffect and useRef is recommended instead.

Tokens
3.1K
Snippets
8
Records
15
Agent score
33%

What's inside react-onclickoutside

  1. Install react-onclickoutside via npm

    master

    Install this Higher Order Component (HOC) if you are using React Class Components.

    Note: If you are using modern React (v16+) with Functional Components and Hooks, it is recommended to implement your own logic using useEffect and useRef instead of installing this HOC.

    $> npm install react-onclickoutside --save
  2. Fix IE11 SVG classList issues

    master

    In IE11, classList is not supported for SVG elements. If your application relies on classList for SVG elements, you must provide a shim. You can use a library like dom4 or use the following manual shim before loading your React code:

    if (!("classList" in SVGElement.prototype)) {
      Object.defineProperty(SVGElement.prototype, "classList", {
        get() {
          return {
            contains: className => {
              return this.className.baseVal.split(" ").indexOf(className) !== -1;
            }
          };
        }
      });
    }
  3. Use onClickOutside with ES6 Class Components

    master

    To use the HOC with a class component, wrap your component with onClickOutside. The wrapped component must implement a handleClickOutside(evt) method. The HOC will then call this method whenever a click occurs outside the component's boundaries.

    import React, { Component } from "react";
    import onClickOutside from "react-onclickoutside";
    
    class MyComponent extends Component {
      handleClickOutside = evt => {
        // ..handling code goes here...
      };
    }
    
    export default onClickOutside(MyComponent);
  4. Use onClickOutside with CommonJS Require

    master

    If you are using CommonJS, you must access the .default property because the library is bundled as an ES6 module.

    // .default is needed because library is bundled as ES6 module
    var onClickOutside = require("react-onclickoutside").default;
    var createReactClass = require("create-react-class");
    
    // create a new component, wrapped by this onclickoutside HOC:
    var MyComponent = onClickOutside(
      createReactClass({
        // ...,
        handleClickOutside: function(evt) {
          // ...handling code goes here...
        }
        // ...
      })
    );
  5. Regulate which events to listen for

    master

    By default, the HOC listens for mousedown and touchstart. You can change this behavior using the eventTypes prop on the wrapped component.

    • Pass a single string for one event type.
    • Pass an array of strings for multiple event types.
  6. Mark elements to be ignored during outside click detection

    master

    You can prevent certain elements from triggering an 'outside click' event by giving them a specific CSS class.

    By default, the HOC ignores any element with the class ignore-react-onclickoutside. You can customize this class name using the outsideClickIgnoreClass prop.

  7. Exclude scrollbar clicks from outside click detection

    master

    By default, clicks on the document scrollbar are treated as outside clicks. To ignore scrollbar clicks, use the excludeScrollbar property.

    This can be passed as a prop to a specific component instance or as a default configuration for all instances via the second argument of onClickOutside.

    // As a prop on a specific instance
    <EnhancedComponent excludeScrollbar={true} />
    
    // As a default configuration for all instances
    var clickOutsideConfig = {
      excludeScrollbar: true
    };
    var EnhancedComponent = onClickOutside(MyComponent, clickOutsideConfig);
  8. Enable or disable outside click listening

    master

    You can control whether the component is actively listening for outside clicks using the disableOnClickOutside prop.

    • Setting disableOnClickOutside={true} prevents the component from setting up event listeners.
    • To enable listening, ensure the prop is false or omitted.

    Note: Avoid calling enableOnClickOutside() or disableOnClickOutside() inside componentDidMount or componentWillMount as it is considered an anti-pattern. Instead, use the disableOnClickOutside prop.

    import React, { Component } from "react";
    import onClickOutside from "react-onclickoutside";
    
    class MyComponent extends Component {
      // ...
      handleClickOutside(evt) {
        // ...
      }
    }
    var EnhancedComponent = onClickOutside(MyComponent);
    
    class Container extends Component {
      render() {
        return <EnhancedComponent disableOnClickOutside={true} />;
      }
    }
  9. Specify a custom click handler via configuration

    master

    If your component does not implement handleClickOutside directly on the instance (or if you are using TypeScript and want to explicitly define the handler), you can pass a configuration object as the second argument to onClickOutside. This object should contain a handleClickOutside function that returns the handler from the component instance.

    import React, { Component } from "react";
    import onClickOutside from "react-onclickoutside";
    
    class MyComponent extends Component {
      // ...
      myClickOutsideHandler(evt) {
        // ...handling code goes here...
      }
      // ...
    }
    
    var clickOutsideConfig = {
      handleClickOutside: function(instance) {
        return instance.myClickOutsideHandler;
      }
    };
    
    var EnhancedComponent = onClickOutside(MyComponent, clickOutsideConfig);
  10. Access the wrapped component instance via getInstance()

    master

    Since react-onclickoutside uses a Higher-Order Component (HOC) pattern, the component you wrap is not directly accessible via a standard React ref. To access the original component's instance and its API (methods, state, etc.), use the getInstance() method provided by the HOC on the ref object.

    Note: There is also a getClass() function available to retrieve the original Class, but it is recommended to access the instance for runtime operations.

    import React, { Component } from 'react'
    import onClickOutside from 'react-onclickoutside'
    
    class MyComponent extends Component {
      // ...
      customFunction() {
        console.log('Called!');
      }
    }
    
    var EnhancedComponent = onClickOutside(MyComponent);
    
    class Container extends Component {
      constructor(props) {
        super(props);
        this.getMyComponentRef = this.getMyComponentRef.bind(this);
      }
    
      someFunction() {
        var ref = this.myComponentRef;
        // 1) Get the wrapped component instance:
        var superTrueMyComponent = ref.getInstance();
        // and call instance functions defined for it:
        superTrueMyComponent.customFunction();
      }
    
      getMyComponentRef(ref) {
        this.myComponentRef = ref;
      }
    
      render() {
        return <EnhancedComponent disableOnClickOutside={true} ref={this.getMyComponentRef}/>
      }
    }
  11. Configure onClickOutsideHOC options

    master

    When using onClickOutsideHOC, you can pass a config object as the second argument to the HOC, or pass props directly to the wrapped component.

    Component Props

    • eventTypes: An array of event names to listen for (e.g., ['mousedown', 'touchstart']). Defaults to ['mousedown', 'touchstart'].
    • excludeScrollbar: Boolean. If true, clicks on the scrollbar will not trigger the outside click handler. Defaults to false.
    • outsideClickIgnoreClass: The CSS class name used to identify elements that should be ignored when determining if a click was "outside". Defaults to ignore-react-onclickoutside.
    • preventDefault: Boolean. If true, calls event.preventDefault() on the detected event. Defaults to false.
    • stopPropagation: Boolean. If true, calls event.stopPropagation() on the detected event. Defaults to false.
    • disableOnClickOutside: Boolean. If true, the component will not start listening for outside clicks on mount.

    Config Object Options

    The config object passed to onClickOutsideHOC(WrappedComponent, config) supports:

    • handleClickOutside: A function that, when called, returns the actual handler function used by the HOC. This is useful for injecting logic during the bootstrapping phase.
    • setClickOutsideRef: A function used to determine which DOM node represents the component. It receives the component instance and should return the node or a ref object.
    • excludeScrollbar: (Same as prop) Sets the default behavior for scrollbar clicks.
  12. Compatibility matrix for React versions

    master

    Choose the appropriate version of react-onclickoutside based on your React version:

    React VersionRecommended react-onclickoutside Version
    0.12 or 0.13v2.4 and below
    0.14v2.5 through v4.9 (uses react-DOM for event bindings)
    15v4.x (offers Mixin and HOC) or v5.x (HOC-only)
    15.5v5.11.x (uses create-react-class)
    16 (or 15.5 prep)v6.x (uses pure class notation)

    Note: Only the latest version receives updates and bug fixes.