maxcountryman maxcountryman - 1 year ago 122
React JSX Question

Is it possible to safely destructure an ES6 React Component class in its constructor signature?

I have an ES6 class which extends

, i.e. a React component. Let's say my component looks like this:

class MyComponent extends React.Component {
constructor({ foo, bar, baz, ...props }) {
super({ foo, bar, baz, ...props });
this.state = { foo, bar, baz };

render() {
return <span>Foo: {} Bar: {} Baz: {this.state.baz}</span>

Here I am using destructuring in the signature of the constructor to pull out some props I would like to use in my component's state. I ensure I pass those values to super. However, when I actually execute similar code I see a warning that looks like this:

Warning: MyComponent(...): When calling super() in
, make
sure to pass up the same props that your component's constructor was

So my question is if it is possible to destructure the constructor's signature like I have shown without the associated warning? (I'm assuming the warning is there for good reason and I'm equally sure I don't fully understand the implications.)

Answer Source

If you look at this line in the React source code, you'll see it does a shallow check to see if the props objects match up.

// other stuff

var propsMutated = inst.props !== publicProps;

// other stuff

  inst.props === undefined || !propsMutated,
  '%s(...): When calling super() in `%s`, make sure to pass ' +
  'up the same props that your component\'s constructor was passed.',
  componentName, componentName

You created a clone of the props when you passed it into super so it raises the warning.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download