Reputation: 1408
What is the correct way to access props in the constructor ? Yes i know that in the React documentation is said that
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 MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(props)
// -> { something: 'something', … }
// absolutely same
console.log(this.props)
// -> { something: 'something', … }
}
}
Are there some cases when to use props
over this.props
?
Upvotes: 13
Views: 12216
Reputation: 419
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
.
Its only about what you prefer, I prefer call always this.props
.
Example:
constructor(props) {
super(props)
this.state = {
isRed: this.props.color === 'red',
}
}
Be sure, that you are calling super(props)
on the first line in your constructor.
Upvotes: 2
Reputation: 222319
this.props
and props
are interchangeable in constructor because this.props === props
, as long as props
is passed to super
. The use of this.props
allows to detect a mistake instantly:
constructor() {
super();
this.state = { foo: this.props.foo }; // this.props is undefined
}
Consistent use of this.props
makes it easier to refactor constructor body:
constructor(props) {
super(props);
this.state = { foo: this.props.foo };
}
to
state = { foo: this.props.foo };
Only this.
needs to be removed.
There are also typing problems with props
in TypeScript, this makes this.props
preferable for typed component.
Upvotes: 23
Reputation: 10874
This recommendation exists to prevent you from introducing errors by calling other methods on the object from the constructor, which depend on this.props
. You don't want to pass props to these explicitly.
E.g. the following would be a bug, because you call doStuff
before super
class MyComponent extends React.Component {
constructor(props) {
this.doStuff()
super(props)
}
doStuff() {
console.log("something is: " + this.props.something)
}
}
Upvotes: 5