Open In App

What’s the difference between super() and super(props) in React ?

Before going deep into the main difference, let us understand what is Super() and Props as shown below:

Keyword ‘this’: The JavaScript this keyword refers to the object it belongs to.



Creating React Application:

Step 1: Create a React application using the following command:



npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

 

Example of Super(): Simple component demonstrating the use of Super() function.

Filename-App.js:




import React from 'react'
  
class MyComponent extends React.Component {
  constructor(props) {
    super()
    console.log(this.props) // Undefined 
    console.log(props)     // Defined Props Will Be Logged 
  }
   
render() {
    return <div>Hello {this.props.message}</div>; // Defined
  }
}
  
export default MyComponent;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Explanation: Here when we are not using props in super() then, when doing console.log(this.props) in console, we will get an undefined message because we are using this.props inside the constructor. But if we just console.log(props) this will give us a proper message in the console on the webpage.

Example of Super(props): Simple component demonstrating the use of Super(props) function.

Filename-App.js:




import React from 'react'
  
class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    console.log(this.props) // {name:'Bob' , .....} Props Will Be Logged 
  }
  
  render() {
    return <div>Hello {this.props.message}</div>; // defined
  }
}
  
export default MyComponent;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Explanation: If we want to use this in the constructor, we need to pass it to super. If we want to use this.props inside the constructor we need to pass it with the super() function. Otherwise, we don’t want to pass props to super() because we see this.Props are available inside the render function.

Note: Outside Constructor() Both will display same value for 'this.props'

Article Tags :