Currently I have built a very simple factory that looks at a JSON config and uses that to dynamically generate components and appropriate props for that component:
let exampleJSON = {
"components": [
{
"type":"ComponentA",
"params": { myProp: "hey there" }
},
{
"type":"ComponentB",
"params": { myOtherProp: "Yo" }
}
]
}
const ComponentA = (props) => {
let { myProp } = props;
return (
<div>{ myProp }</div>
)
}
const ComponentB = (props) => {
let { myOtherProp } = props;
return (
<div>{ myOtherProp }</div>
)
}
const ComponentFactory = (props) => {
const { content } = props;
return (
<div>
{
content.components.map( (component, index) => {
console.log(component);
let Component = "" + component.type;
return (
<Component key={ index } {...component.params } />
)
})
}
</div>
)
};
ReactDOM.render(
<ComponentFactory content={ exampleJSON } />,
document.getElementById('root')
);
Example at: http://codepen.io/jimhill/pen/LboGEY
However, whenever I run this I'm getting the error Unknown prop
myPropon <ComponentA> tag
. If I manually create it however I do not get this error.
Any ideas?
edit: this is fine if I define the elements in an object and reference them by key e.g.
import { render } from 'react-dom';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
const components = {
'ComponentA': ComponentA,
'ComponentB': ComponentB
}
const TheFactory = (props) => {
let Component = components[props.componentType];
return (
<div>
<Component { ...props.componentProps } />
<div>
)
}
render(
<TheFactory componentType="ComponentA" componentProps={ SomeProp:"An example" } />,
document.getElementById('root')
);
Is the below something similar to what you're trying to achieve?
const ComponentA = (props) => {
let { myProp } = props;
return (
<div>{ myProp }</div>
)
}
const ComponentB = (props) => {
let { myOtherProp } = props;
return (
<div>{ myOtherProp }</div>
)
}
let exampleJSON = {
"components": [
{
"type": ComponentA,
"params": { myProp: "hey there" }
},
{
"type": ComponentB,
"params": { myOtherProp: "Yo..." }
}
]
}
const ComponentFactory = (props) => {
const { content } = props;
return (
<div>
{
content.components.map( (component, index) => {
let Component = component.type;
return (
<Component key={ index } {...component.params } />
)
})
}
</div>
)
};
ReactDOM.render(
<ComponentFactory content={ exampleJSON } />,
document.getElementById('root')
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With