I know this is basic but its always good to hear. I prefer this as a discussion rather than a tutorial.
Most people just put super(props) as it will make no harm to code and there is no time in the earth to know the reason why the thing is working, just let it be. Yes, I know that but let's dig deeper into Class Component and find out why do we need super(props) in our constructor.
Q. Why do we need super(props)?
This allow to access this.props in Constructor
Let's explore it:
In fact, the super() function calls the parent class's constructor.
class Clock extends React.Component {
constructor(props){
// super(props); let's put it in comment for now
console.log(this);
}
render() {
console.log(this.props)
}
}
In this code, you are creating a Clock component which is inherited from Parent React.Component.
console.log(this)
Try above code and you will get undefined in console. A child class constructor (which for now is Clock Class) cannot make use of this until super() has been called. Remember I only said constructor
But, there is no effect outside the constructor. it does not affect later rendering or availability of this.props in the render() function.
By calling super(props), you are calling the constructor of React.Component.
Which means that super() is a reference to the parent class constructor() which in the above case is of React.Component which is the base class of Component Clock.
When you pass props to super, the props get assigned to this.
Another thing is that:
If you use super(props), you can call methods that use this.props in from constructor, like this.Home(), without having to pass on the props parameter to those methods/functions.
class Animal {
constructor(home) {
this.shelter = home;
}
}
class Sheep extends Animal {
constructor(props) {
super(props);
this.Home();
}
Home() {
console.log('Sheep lives in' + this.shelter);
}
}
The code explains the statements above code blocks. Here we can call Home() function from the constructor. If you made the close observation, this is just bolstering the things I talked earlier i.e this and remember we are using this.Home() only after we call super().
BONUS and THINK-TANK QUESTION AND ANSWER
Here inside constructor(), we call the super() function with no parameter inside.
{
super();
console.log(this.props); //guess what will be the output here.
}
Can you guess the output?
Yes, it will give an undefined because we called constructor but props are not associated with this which inhibits us to call this.props.
If you have any different ways to present super() or more info, please comment below.
Thank you,
Have a good day and Take care.
Top comments (0)