How to render an array of JSX elements (React components)

13,644

You should use component instead of string in item.type like this

import Foo from './Foo';
import Bar from './Bar';

[ { type: Foo, }, { type: Bar, }, { type: Baz}]

UPDATE:

If you do not have component reference in advance then use a mapping object which convert your string to component reference like this

import Foo from './Foo';
import Bar from './Bar';

const mapper = {
  Foo: Foo,
  Bar: Bar,
}

// Then use it like this

const getItems = this.props.itemslist.map((item, key) => {
    const Type = mapper[item.type];
    rendered.push(<Type data-attributes={attributes} key={key} />);
});
Share:
13,644

Related videos on Youtube

brainstormtrooper
Author by

brainstormtrooper

Updated on June 04, 2022

Comments

  • brainstormtrooper
    brainstormtrooper almost 2 years

    I'm trying to render an array of named react components, say <Foo />, <Bar />, and <Baz />,for example.

    const rendered = [];
    const getItems = this.props.itemslist.map((item, key) => {
    const TYPE = item.type;
    rendered.push(<TYPE data-attributes={attributes} key={key} />);
    });
    return (
      <Grid>
        <Row>
        {rendered}
        </Row>
      </Grid>
    );
    

    I can iterate over my array and see in the console the array of elements, but they are rendered as empty html elements "<foo></foo><bar></bar><baz></baz>", and not the actual components. Why is this happening and, more importantly, how can I get the COMPONENTS to render?

    • brainstormtrooper
      brainstormtrooper over 6 years
      yes, it's a string:
    • Prakash Sharma
      Prakash Sharma over 6 years
      @brainstormtrooper Dont store string in item.type. Instead store component itself.
    • brainstormtrooper
      brainstormtrooper over 6 years
      itemslist: [ { type: 'Foo', }, { type: 'Bar', }, { type: 'Baz', }, ]
    • brainstormtrooper
      brainstormtrooper over 6 years
      @Prakashsharma, How can I do that? I have a config file in javascript... I need to be able to iterate and configure my components...
  • Prakash Sharma
    Prakash Sharma over 6 years
    @brainstormtrooper I am not sure i got you. My point is that from string, you cannot render component. If you do not have component reference then just create a map object which map your string to component.
  • Prakash Sharma
    Prakash Sharma over 6 years
    @brainstormtrooper See this github.com/facebook/react/issues/3365
  • Prakash Sharma
    Prakash Sharma over 6 years
  • brainstormtrooper
    brainstormtrooper over 6 years
    Thank you. I tried that, but I get the same result :-(
  • Shubham Khatri
    Shubham Khatri over 6 years
    Are you string beginning with upperCase character, else it wont be treated as a react component