maxcountryman maxcountryman - 24 days ago 11
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

React.Component
, 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: {this.state.foo} Bar: {this.state.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
MyComponent
, make
sure to pass up the same props that your component's constructor was
passed.


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.)

AR7 AR7
Answer

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

warning(
  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.

Comments