Answer a question

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

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

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐