They say you shouldn't modify the props
in a React Component. Does that extend to modifying them in the constructor?
Specifically,
export default class BookingForm extends React.Component {
constructor(props) {
// am I allowed to modify `props` here?
super(props);
}
}
To be perfectly clear, I'm aware that JavaScript will allow me to do so, I'm asking if this is a bad design pattern that will cause me headache in the future.
I want to re-format some of the props upon initialization; they won't change again after that.
They say you shouldn't modify the props
in a React Component. Does that extend to modifying them in the constructor?
Specifically,
export default class BookingForm extends React.Component {
constructor(props) {
// am I allowed to modify `props` here?
super(props);
}
}
To be perfectly clear, I'm aware that JavaScript will allow me to do so, I'm asking if this is a bad design pattern that will cause me headache in the future.
I want to re-format some of the props upon initialization; they won't change again after that.
Share Improve this question asked Jun 15, 2016 at 4:07 mpenmpen 283k281 gold badges890 silver badges1.3k bronze badges 8 | Show 3 more comments2 Answers
Reset to default 13To re-iterate what zerkms pointed out to me, the answer is no, you are not allowed to modify props
, even in the constructor.
super()
expects the exact same props that you were given, and even if you try to cheat the system by supplying something different, they will be overwritten immediately after the constructor. Ergo, you cannot modify this.props
.
Even if you try to modify the props
object to add an extra property, you will see an error like this:
TypeError: Can't add property bacon, object is not extensible
So you are literally unable the modify the props in the constructor, even if you wanted to.
However, you can set new [JavaScript] properties, e.g.
this.myReformattedProperty = format(props.oldProperty)
You cannot modify the props
, not even in the constructor BUT you can modify a prop. Example:
constructor(props) {
// This won't work. You will get "TypeError: Cannot add property aNewProp, object is not extensible" error.
// props.aNewProp = 'someValue';
// This won't work either. You will get "TypeError: Cannot assign to read only property 'anExistingProp' of object '#<Object>'" error.
// props.anExistingProp = 'someValue';
// However, this will work perfectly:
props.anExistingProp.anExistingOrNewPropertyInThatProp = 'someValue';
super(props);
}
render() {
console.log('this.props are:');
console.log(this.props);
// The print-out includes the modifications that has been made to an existing prop.
}
const
? There's plenty of reasons to modify or set things once and only once. – mpen Commented Jun 15, 2016 at 4:09