Let's say I'm passing many props to a child component. Currently I'm doing:
function ParentComp(){
const [state1, setState1] = useState();
const [state2, setState2] = useState();
function someFunction(){
// code
}
const data = dataReturningFunction(state2);
return(
<ChildComp
state1={state1}
setState1={setState1}
state2={state2}
setState2={setState2}
someFunction={someFunction}
data={data}
// etc...
/>
)
}
function ChildComp(props){
// access everything with props.state1 etc...
}
I'm using the data / code / functions in other children and the parent, so can't just demote it all to the child.
The issue is when this gets to be 10+ properties I'm passing down... lots of repeating myself.
I'm sure there's something straightforward and obvious, but I'm learning, and haven't been able to find an easier way.
You can spread an object like:
function ParentComp(){
const [state1, setState1] = useState();
const [state2, setState2] = useState();
function someFunction(){
// code
}
const data = dataReturningFunction(state2);
const childProps = {
state1,
setState1,
state2,
setState2,
someFunction,
data
};
return(
<ChildComp {...childProps} />
)
}
Just pass an object as a single prop object with all the attributes you need
return(
<ChildComp
propsObj=
{
state1,
setState1,
sate2
// and so on
}
/>
)
And then you can deconstruct props object directly in the child component argument like this
function ChildComponent ({state1,setState1,state2}){
// ...
}
This way you do not have to enter props
prefix when referencing the properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With