Advertisements
I have many props (most of them functions) which i want to pass to sub components.
My initial approach was to pass individual props, but later on it gets bigger and bigger, i become confused
const functionOne...
const functionTwo...
const functionThree...
.
.
.
return (
<Component functionOne={functionOne} functionTwo={functionTwo}....></Component>
)
Then, my second approach is using spread operator and destructure on the sub component.
Still, there are many props and i am still confused.
const props = {functionOne, functionTwo, functionThree}
return (
<Component {...props}></Component>
)
So I try this: grouping multiple props
const propOne = {functionOne, functionTwo, functionThree}
const propTwo = {functionFour, functionFive, functionSix}
return (
<Component propOne={propOne} propTwo={propTwo}></Component>
)
const Component = (propOne, propTwo)=>{
const {functionOne, functionTwo, functionThree} = propOne;
const {functionFour, functionFive, functionSix} = propTwo;
console.log(functionOne) .... undefined....
}
But functions are read "undefined" on the following components.
Any suggestions??
>Solution :
The argument of prop is a singular argument which is why you’re getting undefined. You must use object destructuring to pull out propOne and propTwo from the props argument. Here’s an example below.
You’ll probably want this
const Component = ({ propOne, propTwo })=>{
const {functionOne, functionTwo, functionThree} = propOne;
const {functionFour, functionFive, functionSix} = propTwo;
console.log(functionOne);
return <div>Your component</div>;
}
const App = () => {
return (
<Component
propOne={{ functionOne: 1, functionTwo: 2, functionThree: 3 }}
propTwo={{ functionFour: 4, functionFive: 5, functionSix: 6 }}
/>
)
}