UNPKG

2.63 kBMarkdownView Raw
1# React Clickout
2
3Higher Order Component providing clickout functionality for React components.
4
5[![Build Status](https://travis-ci.org/danielmoi/react-clickout.svg?branch=master)](https://travis-ci.org/danielmoi/react-clickout)
6[![npm version](https://badge.fury.io/js/react-clickout.svg)](https://badge.fury.io/js/react-clickout)
7
8
9## Installation
10With Yarn:
11```
12yarn add react-clickout
13```
14
15With NPM:
16```
17npm install react-clickout
18```
19
20## Usage
21`react-clickout` returns a Higher Order Component that wraps a provided component with the ability to detect a `click` event outside of that component.
22
23Such a "`clickout`" event will call the wrapped component's `handleClickout` method. (Note the character casing.)
24
25See the test suite for more detailed example usage.
26
27```js
28import React, { Component } from 'react';
29import wrapWithClickout from 'react-clickout';
30
31class ToWrap extends Component {
32 constructor() {
33 ...
34 this.state = {
35 isVisible: true,
36 };
37 }
38 handleClickout() {
39 this.setState({
40 isVisible: false,
41 });
42 }
43
44 toggleVisible() {
45 this.setState({
46 isVisible: !this.state.isVisible,
47 });
48 }
49
50 render() {
51 return (
52 <div className="to-wrap__container">
53
54 {this.state.isVisible
55 ?
56 <div className="box" />
57 :
58 null
59 }
60
61 <button onClick={this.toggleVisible} >
62 Toggle Box
63 </button>
64
65 </div>
66 );
67 }
68}
69
70export default wrapWithClickout(ToWrap);
71```
72
73### Excluding elements from calling `handleClickout`
74- it is possible to prevent the `handleClickout` method from being called
75- the elements (outside the component wrapped with `react-clickout`) to be excluded should be marked with the `data-react-clickout` attribute with the value `exclude`
76```js
77<div data-react-clickout="exclude" />
78```
79
80
81## Details
82- React Clickout uses higher order functions (instead of using mixins)
83- React Clickout also uses callback refs (instead of `ReactDOM.findDOMNode)` (which will eventually be deprecated (see [here](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md) and [here](https://github.com/yannickcr/eslint-plugin-react/issues/678#issue-165177220)))
84
85
86
87## Tests
88With Yarn:
89```
90yarn run test
91```
92
93With NPM:
94```
95npm run test
96```
97
98
99## Credits
100Initially a fork from [react-click-outside](https://github.com/kentor/react-click-outside).
101
102Thanks to [Dan Abramov](https://github.com/gaearon) for the solution of [using callback refs](https://github.com/yannickcr/eslint-plugin-react/issues/678#issuecomment-232293175).
103
104## Licence
105
106[Apache-2.0](LICENSE.txt)
\No newline at end of file