Search code examples
javascriptreactjscomponents

Pass a variable to components in an array


I'm stuck with a problem that may be very simple but can't get the solution. I got a page that pass an array of components to a child component.

Here is the page :

mainPage.js

import React from "react";
import Comp1 from "comps/comp1"
import Comp2 from "comps/comp2"
import MyChildComponent from "child/childComponenent"

const MyPage = () => {

let arr = [<Comp1/>, <Comp2/>]

<ChildComponent comps={arr} />

}

export MyPage

The Comp1 looks like this (Comp2 looks more or like the same, with different text) :

comp1.js

import React from "react";
export const Roue = ({ step }) => (
<p>Here is the step {step} </p>
)

And finally I want to access those comps in the child component

childComponenent.js

import React from "react";

const MyChildComponent = ({comps}) => {

const FirstComp = comps[0]
const FirstCompProp = <FirstComp step={1}/>

//console.log(FirstCompProp) works fine

return (
//got an error
{FirstCompProp}
)

}

export MyPage

So I can't render the comps in the child component with the prop, I got this error :

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

What did I get wrong ?

Thanks a lot


Solution

  • FirstComp is already an invoked React component that returns JSX.

    You should change

    let arr = [<Comp1/>, <Comp2/>]
    

    to

    let arr = [Comp1, Comp2]