Eric Sellin
Eric Sellin

Reputation: 668

ReactJS - ES6 class - call super() with augmented properties

This is what I would like to do:

constructor(props, store) {
  props.store = store;
  super(props);
};

I get the following error:

Uncaught TypeError: Can't add property store, object is not extensible

I understand that properties are immutable in ReactJS. So how can I clone, then augment the existing properties?

UPDATE 1

Some background: I'm basically trying to avoid a this._store "private" variable, and would rather have it in the props, since the value is known at object creation time and will not change.

My class hierarchy is as follows:

import SpeakersStore from ...;
class SpeakersViewController extends ItemsViewController {
  constructor(props) {
    super(props, SpeakersStore);
  };
  ...
};

class ItemsViewController extends React.Component {
  constructor(props, store) {
    props.store = store;
    super(props);
  };
  ...
};

Upvotes: 2

Views: 174

Answers (1)

rossipedia
rossipedia

Reputation: 59427

You should be able to do the following:

constructor(props, store) {
  super({...props, store});
}

If you're in an environment where the object spread operator (the {...props} construct) is not available, then you can use Object.assign:

constructor(props, store) {
  super(Object.assign({}, props, {store});
}

However, if this is a constructor for a React component, be aware that the second argument to the constructor for React.Component is context, and you won't get the behavior you're looking for.

Upvotes: 2

Related Questions