Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from "react";
- import PropTypes from "prop-types";
- class OutsideClickHandler extends React.Component {
- static propTypes = {
- children: PropTypes.node,
- className: PropTypes.string,
- onOutsideClick: PropTypes.func,
- };
- static defaultProps = {
- children: null,
- className: null,
- onOutsideClick: null,
- };
- componentDidMount() {
- const { onOutsideClick } = this.props;
- document.addEventListener(
- "mousedown",
- this.handleClickOutside(onOutsideClick),
- );
- }
- componentWillReceiveProps(nextProps) {
- if (nextProps.onOutsideClick !== this.props.onOutsideClick) {
- // Remove previous listener
- document.removeEventListener(
- "mousedown",
- this.handleClickOutside(this.props.onOutsideClick),
- );
- // Attach the new listener
- document.addEventListener(
- "mousedown",
- this.handleClickOutside(nextProps.onOutsideClick),
- );
- }
- }
- componentWillUnmount() {
- // Remove the last listener
- const { onOutsideClick } = this.props;
- document.removeEventListener(
- "mousedown",
- this.handleClickOutside(onOutsideClick),
- );
- }
- setRef = (node) => {
- this.componentRef = node;
- };
- handleClickOutside = onOutSideClick => (event) => {
- if (
- this.componentRef &&
- !this.componentRef.contains(event.target) &&
- typeof onOutSideClick === "function"
- ) {
- onOutSideClick();
- }
- };
- render() {
- const { children, className, ...rest } = this.props;
- return (
- <div ref={this.setRef} className={className} {...rest}>
- {children}
- </div>
- );
- }
- }
- export default OutsideClickHandler;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement