Skip to content

Commit 2f213ef

Browse files
committed
feat: add basic <OutsideClick> implementation
1 parent 7f10453 commit 2f213ef

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "libreact",
3-
"version": "0.17.0",
3+
"version": "1.0.0",
44
"description": "React standard library",
55
"main": "lib/index.js",
66
"repository": {

src/OutsideClick/index.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import {Component, cloneElement, Children} from 'react';
2+
import {on, off, noop} from '../util';
3+
4+
export interface IOutsideClickProps {
5+
onClick?: (event?) => void;
6+
}
7+
8+
export interface IOutsideClickState {
9+
}
10+
11+
class OutsideClick extends Component<IOutsideClickProps, IOutsideClickState> {
12+
el: HTMLElement;
13+
14+
ref = (originalRef) => (el) => {
15+
this.el = el;
16+
(originalRef || noop)(el);
17+
};
18+
19+
componentDidMount () {
20+
on(document, 'mousedown', this.onClickOutside);
21+
}
22+
23+
componentWillUnmount () {
24+
off(document, 'mousedown', this.onClickOutside);
25+
}
26+
27+
onClickOutside = (event) => {
28+
if (this.el && !this.el.contains(event.target)) {
29+
(this.props.onClick || noop)(event);
30+
}
31+
};
32+
33+
render () {
34+
const {children} = this.props;
35+
const element = Children.only(children);
36+
37+
if (!element) {
38+
return null;
39+
}
40+
41+
return cloneElement(element, {
42+
...element.props,
43+
ref: this.ref((element as any).ref)
44+
});
45+
}
46+
}

0 commit comments

Comments
 (0)