I have a list of keys which represent a custom React component. Based on this list I want to render the appropriate component. I have a reference to each component so I can create a map of key -> Component
which allows me to create a list of my components. However I have not found a way to render this list.
Example.:
input: ["componentA", "componentB", "componentC"]
output:
<ComponentA />
<ComponentB />
<ComponentC />
This is what I got so far, however I'm not sure how to render the list of components:
function renderElements(keys) {
const components = {
componentA: ComponentA,
componentB: ComponentB,
componentC: ComponentC,
};
const componentsToRender = keys.map(key => components[key]);
return (
<div>
{componentsToRender}
</div>
);
}
What worked for me:
render() {
const components = [ComponentA, ComponentB, ComponentC] // references to components
return (
<div>
{components.map((comp, i) => React.createElement(comp, { key: i })}
</div>
);
}
Had to use a reference to the component and had to use React.createElement
due to problems with nested JSX (might be Typescript related).
Try this. It should work.
render()
{
const input=["ComponentA", "ComponentB", "ComponentC"]
return(
<div>
{
input.map((comp,i)=>){
return <{comp} key={i} />
}
}
</div>
)
}
Note: input= ["ComponentA", "ComponentB", "ComponentC"];Custom component name should be in Capital
render() {
return (
<div>
{componentsToRender.map((Component, key) => (<Component key={key}/>))}
<div>
);
}
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