Reactjs Fix Must call a super constructor in derived class before accessing this
This tutorial explains an error Must call a super constructor in the derived class before accessing this in react
First, let’s create a react component
import React from "react";
class CssStyles extends React.Component {
constructor() {}
render() {
return (
<div>
<button value="submit"></button>
</div>
);
}
}
export default CssStyles;
And called the above class in another react component
import React from "react";
import CssStyles from "./css-styles";
function App() {
return (
<div className="App">
<CssStyles></CssStyles>
</div>
);
}
export default App;
It throws an error for react component as Uncaught ReferenceError: Must call a super constructor in derived class before accessing ‘this’ or returning from derived constructor
Fix for calling a super constructor in derived class before accessing ‘this’ or returning from the derived constructor
We created a class with ES6 syntax.
React create an instance of this react class
Solution and Fix for this
- React component extends React. Component, React. the component is a base class the derived class is an extended class. In the Derived class,- If it has a constructor, The first line in the constructor is to call super() before calling this keyword in the component.
If no constructor is defined in a constructor, This error will not come, It calls the default constructor of a superclass.
For example, Let’s try to understand how Inherited classes work in ES6.
Define base class Animal with the type attribute.
class Animal {
constructor() {
this.type = "animal";
}
}
Define Child or derived class Lion by inheriting (Extend) Animal class In Constructor,
- You called this. type before super(). Which is not correct and invalid Valid is, Child constructor this keyword not used and called before declaring
super()
, means super() must be the first line in ES-derived class constructor if you have constructor defined. this
call works after the super() statement as given below
class Lion extends Animal {
constructor() {
console.log(this.type); // gives an error ReferenceError
super();
console.log(this.type); // This works and print Animal
}
}
Created One more class by extending Lion class No constructor is defined, No error and valid.
class MasaiLion extends Lion {}
var lion = new Lion(); // Animal
var masaiLion = new MasaiLion(); // Animal
Hope you understand the ES6 classes inheritance and this, super statement usage.
In the same way, we have to implement React class components as these are following ES2015 standards.
Conclusion
In a summary, ES6 class components must follow the below guidelines for creating a react component.
- Derived class constructor, calling
this
gives a ReferenceError before the call to super() - Derived class constructor must contain the first line to call the superclass constructor which initializes the data inside the superclass
- If there is no constructor, These rules do not apply and work as expected