Skip to content

Commit

Permalink
feat: add basic <OutsideClick> implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 27, 2018
1 parent 7f10453 commit 2f213ef
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "libreact",
"version": "0.17.0",
"version": "1.0.0",
"description": "React standard library",
"main": "lib/index.js",
"repository": {
Expand Down
46 changes: 46 additions & 0 deletions src/OutsideClick/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {Component, cloneElement, Children} from 'react';
import {on, off, noop} from '../util';

export interface IOutsideClickProps {
onClick?: (event?) => void;
}

export interface IOutsideClickState {
}

class OutsideClick extends Component<IOutsideClickProps, IOutsideClickState> {
el: HTMLElement;

ref = (originalRef) => (el) => {
this.el = el;
(originalRef || noop)(el);
};

componentDidMount () {
on(document, 'mousedown', this.onClickOutside);
}

componentWillUnmount () {
off(document, 'mousedown', this.onClickOutside);
}

onClickOutside = (event) => {
if (this.el && !this.el.contains(event.target)) {
(this.props.onClick || noop)(event);
}
};

render () {
const {children} = this.props;
const element = Children.only(children);

if (!element) {
return null;
}

return cloneElement(element, {
...element.props,
ref: this.ref((element as any).ref)
});
}
}

0 comments on commit 2f213ef

Please sign in to comment.