Reputation: 1386
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.
Upvotes: 6
Views: 4754
Reputation: 356
Two ways you can use to pass props to child components
1.
return(
<ChildComp
{...this}
/>
)
{...this}
will send whole current class component to child component and it will receive all varialbles, states, props and methods
First option is preferred
Upvotes: 2
Reputation: 360
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
Upvotes: 5
Reputation: 74096
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} />
)
}
Upvotes: 9