Skip to content

Commit 3a6cb33

Browse files
committed
escape if there is no ref.current
1 parent 4fe8315 commit 3a6cb33

File tree

2 files changed

+17
-12
lines changed

2 files changed

+17
-12
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "use-custom-element",
3-
"version": "1.0.3",
3+
"version": "1.0.4",
44
"description": "",
55
"main": "lib/index.js",
66
"scripts": {

src/index.js

+16-11
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,24 @@ const useCustomElement = (props, customMapping = {}) => {
44
const ref = React.createRef();
55

66
React.useLayoutEffect(() => {
7-
const fns = Object.keys(props)
8-
.filter(key => props[key] instanceof Function)
9-
.map(key => ({
10-
key: customMapping[key] || key,
11-
fn: customEvent =>
12-
props[key](customEvent.detail, customEvent),
13-
}));
14-
15-
fns.forEach(({ key, fn }) =>
16-
ref.current.addEventListener(key, fn),
17-
);
7+
let fns;
8+
9+
if (ref.current) {
10+
fns = Object.keys(props)
11+
.filter(key => props[key] instanceof Function)
12+
.map(key => ({
13+
key: customMapping[key] || key,
14+
fn: customEvent =>
15+
props[key](customEvent.detail, customEvent),
16+
}));
17+
18+
fns.forEach(({ key, fn }) =>
19+
ref.current.addEventListener(key, fn),
20+
);
21+
}
1822

1923
return () =>
24+
ref.current &&
2025
fns.forEach(({ key, fn }) =>
2126
ref.current.removeEventListener(key, fn),
2227
);

0 commit comments

Comments
 (0)