user7319004
user7319004

Reputation:

Is there a way to pass a group of props in react?

The way I actually use works well but my props keep growing and I wondering if I can group them into one single state and pass it to the child, this is my code:

    <Panel
      uniqueIDs={uniqueIDs}
      userID={userID}
      loading={loading}
      premium={premium}
      percent={percent}
      total={total}
      until={until}
      user={user}
      done={done}
    />

After the render I define those variable like so :

let { loading, empty, total, uniqueIDs, slice, percent, until, ok, user, premium, data, keys, done, userID } = this.state;

Can i just send this.state variable? I made a little bit of research I didn't find any solution to my issue, I know I can use third-party libraries to manage state but I am trying to keep it simple.

Upvotes: 1

Views: 2966

Answers (2)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

Yes, you definitely could just pass your entire state-variable into your child-component as multiple properties

<Child {...this.state}/>

This would be perfectly acceptable.

If your state is {id: 1, name: 2}

You would still be able to access the props in your child-component as

props.id or this.props.id
props.name or this.props.name

As a note you should be cognizant of component re-rendering. If you make many updates to the state in your parent-component this will also cause your Child component to re-render a lot as well, which could have performance issues.

To workaround this, make sure to employ methods like componentDidUpdate() for class-components and react-hooks for functional components. These can help control the flow of re-rendering.

Upvotes: 3

Vivek
Vivek

Reputation: 174

you can make an object for the props you are sending and can use spread operator

  let props = {
        uniqueIDs : uniqueIDs,
        userID:userID,
        loading:loading,
        premium:premium
          }
<Panel {...props} />

In panel component you can use this.props.uniqueIDs ans so on.

Upvotes: 5

Related Questions