Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react passing groups of multiple props

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }}
    />
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading