Home > Net >  How can i render a component by a for loop?
How can i render a component by a for loop?

Time:09-16

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

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

CodePudding user response:

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.

CodePudding user response:

You just need to change your code to this:

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