Before going deep into the main difference, let us understand what is Super() and Props as shown below:
- Super(): It is used to call the constructor of its parent class. This is required when we need to access some variables of its parent class.
- Props: It is a special keyword that is used in react stands for properties. Used for passing data from one component to another. Props data is read-only, which means that data coming from the parent should not be changed by child components.
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.
Example of Super(): Simple component demonstrating the use of Super() function.
Filename-App.js:
Javascript
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:
Javascript
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'