Home > database >  Can I store a component in a variable and push children to it after it has been created?
Can I store a component in a variable and push children to it after it has been created?

Time:08-18

Lets say that I have this component:

const Test = ({ children, ...rest }) => {
    return <>{children}</>
};

export default Test;

I am wondering if it is possible to create a variable that holds the component like this:

const test = <Test></Test>;

And then loop over some data and push children to the test variable on every iteration.

CodePudding user response:

if you don't have the data yet, then all you have to do is conditionally render your component when you do have the data.

{ data ? (<Test>{data.map(...)}</Test>) : <SomeOtherComponent /> /* or null */}

or

{ data ? <>{data.map((x) => <Test>{x}</Test>)}</> : <SomeOtherComponent /> /* or null */}

depending on what you want achieve, i didn't fully understand your question

i.e. if you have the data you need, render the component, rendering the children as you see fit, otherwise render some other component (or null, to render nothing)

CodePudding user response:

Yeap, try that pattern:

const test = (children) => <Test>{children}</Test>;

and usage

<>
{[1,2,3].map(el=>test(el))}
</>

[Edited]

const TestComp = ({children}) => <Test>{children}</Test>;

<>
{[1,2,3].map(el=>(<TestComp>{el}</TestComp>))}
</>
  • Related