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.
The correct way is - don`t use props in your constructor - just send into a parent. But both way is working. So, there is one special case for reading props in a constructor and it is set default state from props. In a constructor after call super (props) are this.props and props equals. this.props = props.
Props in the Constructor If your component has a constructor function, the props should always be passed to the constructor and also to the React.Component via the super () method.
When implementing the constructor for a React.Component subclass, you should call super (props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs To be more clear , why do wee need this.props if we can just use props inside constructor
class Main extends React.Component { constructor (props) { //etc, etc... } // etc, etc... } Can anyone tell me why? All the attributes of a react component in JSX are called “props”. So when you have a component like: It will receive an object as the props parameter, with bar and xyzzy keys. In other words, it’s automatically passed for you.
To 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With