When implementing the constructor()
function inside a React component, super()
is a requirement. Keep in mind that your MyComponent
component is extending or borrowing functionality from the React.Component
base class.
This base class has a constructor()
function of its own that has some code inside of it, to setup our React component for us.
When we define a constructor()
function inside our MyComponent
class, we are essentially, overriding or replacing the constructor()
function that is inside the React.Component
class, but we still need to ensure that all the setup code inside of this constructor()
function still gets called.
So to ensure that the React.Component
’s constructor()
function gets called, we call super(props)
. super(props)
is a reference to the parents constructor()
function, that’s all it is.
We have to add super(props)
every single time we define a constructor()
function inside a class-based component.
If we don’t we will see an error saying that we have to call super(props)
.
The entire reason for defining this constructor()
funciton is to initialize our state object.
So in order to initialize our state object, underneath the super call I am going to write:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
// React says we have to define render()
render() {
return <div>Hello world</div>;
}
};
So we have defined our constructor()
method, initialized our state object by creating a JavaScript object, assigning a property or key/value pair to it, assigning the result of that to this.state
. Now of course this is just an example here so I have not really assigned a key/value pair to the state object, its just an empty object.