with-click-outside

1.0.1 • Public • Published

withClickOutside

Build Status codecov npm version License: MIT PRs Welcome

The High Order Component which allows you to detect the current click is outside or inside of a component.

Chợ Tốt header

Table Content

Installation

npm

npm i with-click-outside

yarn

yarn add with-click-outside

Parameters

withClickOutside retrieves 2 params.

React Component

node

id

string

Usage

import withClickOutside from 'with-click-outside';
import Component from './Component';
 
const WrappedComp = withClickOutside(Component, 'id_of_component');

You can check out the basic demo here: https://codesandbox.io/s/yj9m75734j

import React from 'react';
import ReactDOM from 'react-dom';
 
import withClickOutside from 'with-click-outside';
 
class DropDown extends React.Component {
  constructor() {
    super();
    this.state = { open: false };
  }
 
  componentWillReceiveProps(nextProps) {
    if (nextProps.outside !== this.props.outside) {
      this.setState({
        open: !nextProps.outside,
      });
    }
  }
 
  toggle = () => {
    this.setState({ open: !this.state.open });
  };
 
  render() {
    const { open } = this.state;
    const { outside, id } = this.props;
    return (
      <div>
        <p>{outside ? 'outside' : 'inside'}</p>
        <div id={id}>
          <button onClick={this.toggle}>toggle</button>
          {open &&
            !outside && (
              <ul>
                <li>item 1</li>
                <li>item 2</li>
                <li>item 3</li>
              </ul>
            )}
        </div>
      </div>
    );
  }
}
const WrappedDropDown = withClickOutside(DropDown, 'idDropDown');
ReactDOM.render(<WrappedDropDown />, document.getElementById('root'));

Examples

Dependents (0)

Package Sidebar

Install

npm i with-click-outside

Weekly Downloads

3

Version

1.0.1

License

none

Unpacked Size

567 kB

Total Files

29

Last publish

Collaborators

  • dzungnguyen179