-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathDynamicComponent.jsx
50 lines (42 loc) · 1.23 KB
/
DynamicComponent.jsx
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
50
import { isFunction, isString } from "lodash";
import React from "react";
import PropTypes from "prop-types";
const componentsRegistry = new Map();
const activeInstances = new Set();
export function registerComponent(name, component) {
if (isString(name) && name !== "") {
componentsRegistry.set(name, isFunction(component) ? component : null);
// Refresh active DynamicComponent instances which use this component
activeInstances.forEach(dynamicComponent => {
if (dynamicComponent.props.name === name) {
dynamicComponent.forceUpdate();
}
});
}
}
export function unregisterComponent(name) {
registerComponent(name, null);
}
export default class DynamicComponent extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
children: PropTypes.node,
};
static defaultProps = {
children: null,
};
componentDidMount() {
activeInstances.add(this);
}
componentWillUnmount() {
activeInstances.delete(this);
}
render() {
const { name, children, ...props } = this.props;
const RealComponent = componentsRegistry.get(name);
if (!RealComponent) {
return children;
}
return <RealComponent {...props}>{children}</RealComponent>;
}
}