|
| 1 | +var React = require('react'); |
| 2 | +var OnClickOutsideMixin = require('react-onclickoutside'); |
| 3 | + |
| 4 | + |
| 5 | +/** |
| 6 | + * @function listenToClickOutside |
| 7 | + * |
| 8 | + * A wrapper for ES6 React classes to use the `onClickOutside` event handler: |
| 9 | + * |
| 10 | + * import listenToClickOutside from 'react-onclickoutside/listenToClickOutside.js'; |
| 11 | + * |
| 12 | + * class Es6Component extends React.Component { |
| 13 | + * handleClickOutside = (event) => { |
| 14 | + * // ...handling code goes here... |
| 15 | + * } |
| 16 | + * } |
| 17 | + * |
| 18 | + * export default listenToClickOutside(Es6Component); |
| 19 | + * |
| 20 | + * Alternatively you can pass the handler down from the parent on an `onClickOutside` prop: |
| 21 | + * |
| 22 | + * class Child extends React.Component { |
| 23 | + * // No event handler here, if provided this handler takes precedence and the one passed down |
| 24 | + * // is not called automatically. If it should be, call it on the props from the child handler. |
| 25 | + * } |
| 26 | + * |
| 27 | + * Child = listenToClickOutside(Child); |
| 28 | + * |
| 29 | + * |
| 30 | + * class Parent extends React.Component { |
| 31 | + * handleClickOutside = (event) => { |
| 32 | + * // ...handling code goes here... |
| 33 | + * } |
| 34 | + * |
| 35 | + * render() { |
| 36 | + * return ( |
| 37 | + * <Child onClickOutside={this.handleClickOutside}/> |
| 38 | + * ); |
| 39 | + * } |
| 40 | + * } |
| 41 | + * |
| 42 | + * @param {React.Component} Component The component outside of which to listen to clicks. |
| 43 | + * @returns {React.Component} |
| 44 | + */ |
| 45 | +function listenToClickOutside(Component) { |
| 46 | + |
| 47 | + return React.createClass({ |
| 48 | + |
| 49 | + displayName: (Component.displayName || Component.name) + 'ClickOutside', |
| 50 | + |
| 51 | + mixins: [OnClickOutsideMixin], |
| 52 | + |
| 53 | + handleClickOutside: function(event) { |
| 54 | + if (this.refs.inner.handleClickOutside) { |
| 55 | + return this.refs.inner.handleClickOutside(event); |
| 56 | + } |
| 57 | + if (this.props.onClickOutside) { |
| 58 | + return this.props.onClickOutside(event); |
| 59 | + } |
| 60 | + }, |
| 61 | + |
| 62 | + render: function render() { |
| 63 | + return React.createElement(Component, Object.assign({ref: 'inner'}, this.props)); |
| 64 | + } |
| 65 | + }); |
| 66 | +} |
| 67 | + |
| 68 | +module.exports = listenToClickOutside; |
0 commit comments