abu abu
abu abu

Reputation: 7022

Merge State and Props in React

In one of my component I have this.props.errors and this.state.errors. In this component any one of them is present. I would like to merge them to pass to child component like below.

<ChildComponent errors = { this.props.errors/this.state.errors } />

How can I do that ?

Upvotes: 0

Views: 2089

Answers (4)

andy mccullough
andy mccullough

Reputation: 9571

I wouldn't recommend the other solutions that are simply using a spread, as they are spreading into a new object each time, which would cause a rerender each time on a PureComponent.

Create an object outside of the render function, e.g. as a class member variable, or state property and populate the errors into that object.

class Parent extends React.PureComponent {
   constructor(props){
      super(props)
      this.state = {
         allErrors: {
            ...yourStateErrors,
            ...this.props.errors
         }
      }

   }
   ...
   render() {
      <Child errors={this.state.allErrors} />
   }
}

Remembering not to just mutate the state.errors property on any further updates

Upvotes: 0

AdamGold
AdamGold

Reputation: 5051

You can use the built-in spread operator:

<ChildComponent errors={{ ...this.props.errors, ...this.state.errors }} />

Upvotes: 2

Avin Kavish
Avin Kavish

Reputation: 8947

You can use the object spread operator to merge the keys and create a new object.

<ChildComponent errors = { {...this.props.errors, ...this.state.errors} } />

Note that the order of the two spreads are important, in the example above keys from the state object will override keys of the same name in the props object.

Edit: If the errors are strings you can either join them or pass them as an array.

<ChildComponent errors = { [this.props.errors, this.state.errors] } />
<ChildComponent errors = { this.props.errors + ' ' + this.state.errors } />

Upvotes: 2

Brad Ball
Brad Ball

Reputation: 619

you gotta use the spread operator

<ChildComponent errors={{ ...this.props.errors, ...this.state.errors }} />

Upvotes: 1

Related Questions