Cannot display embedded array of react components

Viewed 20

I have the following situation :

I have a parent component that wants to display an array of child components (3 to be exact..). However the "arrayOfComponents" does not display when I render ParentComponent.

The code looks like this :

let arrayOfComponents =
    [1,2,3].map(() => {
        return (props) => <div>TEST {props.position}</div>
    })

let ParentComponent = () => {
    return <>
        <div>Show Me Three Elements</div>
        <div>the length of array is {arrayOfComponents && arrayOfComponents.length} </div>
        <div>
        {arrayOfComponents && arrayOfComponents.map((e, i) => {
            return <div><e position={i}/></div>
        })}
        </div>
    </>
}

I expected :

Show Me Three Elements
the length of array is 3
TEST 1
TEST 2
TEST 3

but instead I get

Show Me Three Elements
the length of array is 3

I assumed that you can just display each element in the array in JSX form like so :

<e position={i}/>

Am I doing this correctly?

1 Answers

you can define arrayOfComponents as an array of numbers [1,2,3] and inside the ParentComponent you can put a map loop like this

{arrayOfComponents && arrayOfComponents.map((value, i) => {
            return (<div>TEST {value}</div>)
})}

no need to complicate things i think this is the best approach for it

Related