Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing lots of props to react children

Tags:

reactjs

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.

like image 664
Trees4theForest Avatar asked Dec 31 '22 18:12

Trees4theForest


2 Answers

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} />
  )
}
like image 186
CD.. Avatar answered Jan 08 '23 01:01

CD..


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

like image 42
Jørgen Avatar answered Jan 08 '23 01:01

Jørgen