I'm using functional components. I have built my separate components and am placing them into my index.js
file.
Right now the structure of the components is (pseudocode):
<App stateVariable1={x} stateVariable2={y} stateVariable3={z}>
<ChildOne props1={x} props2={y} />
<ChildTwo props1={z}/>
</App>
ChildOne and ChildTwo are currently rendered within App.js
, and so passing the state variables to the two children is very easy.
I'd like to extract the rendered children into index.js
and replace the two children with a {props.children} within App.js
, to increase the SRP of the component and make it more reusable.
However I am struggling with understanding how to pass multiple state variables as multiple props to props.children
within my index.js
file.
I have read the react documentation for Render Props and that deals with one prop being passed to a single child, rather than multiple children which want to receive different props.
How do I go about achieving what I would like to do?
UPDATE
I have attempted to use render props as per the accepted answer here: How to pass props to {this.props.children}
My index.js
looks like this:
ReactDOM.render(
<React.StrictMode>
<App>
{(stateVariable1) => (
<Fragment>
<ChildOne props1={stateVariable1} props2={stateVariable2} />
<ChildTwo props3={stateVariable3} />
</Fragment>
)}
</App>{' '}
</React.StrictMode>,
document.getElementById('root')
);
However all of the props/stateVariables through undefined errors, as of course they're not defined in index.js
.
Where am I going wrong?
Update 2: Solution
I passed all of the state variables as arguments to the render props and this has solved the issue:
ReactDOM.render(
<React.StrictMode>
<App>
{(stateVariable1, stateVariable2, stateVariable3) => (
<Fragment>
<ChildOne props1={stateVariable1} props2={stateVariable2} />
<ChildTwo props3={stateVariable3} />
</Fragment>
)}
</App>{' '}
</React.StrictMode>,
document.getElementById('root')
);
Is there a way to deconstruct this so that I don't need to pass each argument into the callback? I am using functional components so state is stored in multiple variables rather than within the class components' state object.