Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  139] [ 6]  / answers: 1 / hits: 21526  / 7 Years ago, mon, april 24, 2017, 12:00:00

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>
);
}

More From » reactjs

 Answers
9

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).


[#58035] Friday, April 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
davism

Total Points: 339
Total Questions: 100
Total Answers: 100

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;