Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Render dynamic list of components

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>
  );
}
like image 812
fwind Avatar asked Apr 24 '17 10:04

fwind


3 Answers

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

like image 74
fwind Avatar answered Oct 10 '22 12:10

fwind


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

like image 32
Ved Avatar answered Oct 10 '22 12:10

Ved


render() {
    return (
       <div>
          {componentsToRender.map((Component, key) => (<Component key={key}/>))}
       <div>
    );
  }
like image 23
user6223966 Avatar answered Oct 10 '22 14:10

user6223966