UNPKG

react-click-outside-component

Version:

ClickOutside component for React

38 lines (29 loc) 832 B
import React, { Component } from 'react' import PropTypes from 'prop-types' export default class ClickOutside extends Component { static propTypes = { onClickOutside: PropTypes.func.isRequired }; constructor(props) { super(props) this.getContainer = this.getContainer.bind(this) } getContainer(ref) { this.container = ref } render() { const { children, onClickOutside, ...props } = this.props return <div {...props} ref={this.getContainer}>{children}</div> } componentDidMount() { document.addEventListener('click', this.handle, true) } componentWillUnmount() { document.removeEventListener('click', this.handle, true) } handle = e => { const { onClickOutside } = this.props const el = this.container if (!el.contains(e.target)) onClickOutside(e) }; }