/
index.js
49 lines (37 loc) · 1.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React from 'react';
const useCustomElement = (props, customMapping = {}) => {
const ref = React.createRef();
React.useLayoutEffect(() => {
const { current } = ref;
let fns;
if (current) {
fns = Object.keys(props)
.filter(key => props[key] instanceof Function)
.map(key => ({
key: customMapping[key] || key,
fn: customEvent =>
props[key](customEvent.detail, customEvent),
}));
fns.forEach(({ key, fn }) => current.addEventListener(key, fn));
}
return () => {
if (current) {
fns.forEach(({ key, fn }) =>
current.removeEventListener(key, fn),
);
}
};
}, [customMapping, props, ref]);
const customElementProps = Object.keys(props)
.filter(key => !(props[key] instanceof Function))
.reduce((acc, key) => {
const prop = props[key];
const computedKey = customMapping[key] || key;
if (prop instanceof Object || prop instanceof Array) {
return { ...acc, [computedKey]: JSON.stringify(prop) };
}
return { ...acc, [computedKey]: prop };
}, {});
return [customElementProps, ref];
};
export default useCustomElement;