Sunday, November 17, 2024
Google search engine
HomeLanguagesWhat is the purpose of using super constructor with props argument in...

What is the purpose of using super constructor with props argument in ReactJS ?

React is a free and open-source JavaScript library for UI design. It renders the components written in JSX. It introduces the concept of props. Props are used to pass data from parent components to child components.  These props can be updated only by the parent component. It is read-only for child components.  We might require props inside the child component constructor with this keyword.  Super() function calls the constructor of the parent class. Using super constructor with props arguments basically allows accessing this.props in a Constructor function.

Let us create a React project and then we will create a UI to showcase the above purpose. Users will be able to see the application of the super constructor with props argument.

Creating React Project:

Step 1: Create a react application by typing the following command in the terminal.

npx create-react-app project_name

Step 2: Now, go to the project folder i.e. project_name by running the following command.

cd project_name

Project Structure: It will look like the following:

Project Structure

Example: Let us create a super constructor with props argument. 

App.js




import React from "react";
  
class App extends React.Component {
   
  constructor(props){
    super(props);
    console.log("Empty props ", this.props);
  }
  
  render() {
    return (
      <div>
        <p>Hello World!</p>
      </div>
    );
  }
}
  
export default App;


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

npm start

Output: Open your browser. It will by default open a tab with localhost running. As shown in the image, the props are getting logged into the console. Here props have nothing in it that’s why it is an empty object. 

this.props log 

You can even look through these GFG articles for further clarity:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments