Use of super() method inside constructor of the component
The super() is used inside the constructor for the purpose of getting access to this keyword inside our constructor. Super is a keyword in JavaScript and is used to call super or parent class in the hierarchy. React class extends React Component with ES6 syntax. If we would like to set a property or access this inside the constructor we need to call the super() method.Â
Prerequisites:
Steps to create 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:
cd filename
Project Structure:
Project Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example 1: This example will illustrate the use of super() inside the constructor of the component
Javascript
import React from 'react'
class MyComponent extends React.Component {
constructor() {
console.log( this )
}
render() {
return <div>Super Concept</div>;
}
}
export default MyComponent;
|
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Example 2: This example illustrates the code by solving that error we use super() in the constructor.
Javascript
import React from 'react'
class MyComponent extends React.Component {
constructor() {
super ()
console.log( this )
}
render() {
return <div>Super Concept</div>;
}
}
export default MyComponent;
|
Output:
Output
Last Updated :
04 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...