How can i render a component by a for loop?

Viewed 47

I have an array of components, so I want to print the content. My attempt is like this:

const fields = [<Invites />]

return (
    <Card style={{ width: 600 }}>
        {fields.map((Item, index) => <Item />)}
    </Card>
)

But, I got this error:

react-dom.development.js:28439 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

BTW, this is the <Invites /> component:

const Invites = () => {
    return (
        <Form.Item className='form-item item-container' label="Invites">
            <span>
                <Input />
            </span>
        </Form.Item>
    )
}
2 Answers

Since each item in fields is already an element, you don't need to do anything at all:

const fields = [<Invites />];

return (
    <Card
        style={{ width: 600 }}
    >
        {fields}
    </Card>
);

React will always do its best to render arrays, and in the case of an array of elements, it renders them all for you.


To add keys you can also use React.Fragment:

return (
    <Card
        style={{ width: 600 }}
    >
        {fields.map((item, index) => <React.Fragment key={index}>{item}</React.Fragment>)}
    </Card>
);

You just need to change your code to this:

{fields.map((item, index) => item)}
Related