2

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);
  };
  ...
};
2
  • What is the scenario here? I don't think that you can do such a thing in React. But I can imagine that there is a way around the problem. Commented Feb 16, 2016 at 16:05
  • Why not pass the store as another prop from the parent component or React.createElement call? Commented Feb 16, 2016 at 16:09

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Better to use Object.assign since this question mentioned nothing about ES7 or Babel.
I'm using Babel so no worries about spreads... Your code makes sense and looks like it should work, but I still end up with the same props, i.e. without my extra store.
Gonna need more info then. How is your class being constructed? Is it a React component? (If so, see my last paragraph above). How is the store being constructed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.