Use of super() method inside constructor of the component
The super() is used inside the constructor for the purpose to get access to this keyword inside our constructor. With this let’s try to understand super() first.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app filename
Step 2: After creating your project folder i.e. example, move to it using the following command:
Project structure: It will look like this:
Example 1: This example will illustrate the use of super() inside the constructor of the component:
Step to Run Application: Run the application using the following command from the root directory of the project:
When running the above code then we get an error that this is not allowed before super(). Now open your browser and go to http://localhost:3000/, you will see the following output:
To solve that error, we use super() in the constructor. Therefore, whenever we want to access this inside the constructor then we need to super() inside the constructor.
Example 2: This example illustrates the code by solving that error we use super() in the constructor.
Now, we can have access to this in our constructor and use it to have access to the props if that has been passed to the component.
Please Login to comment...