React Constructor and Super Keyword
Constructor: Constructor is a method that is used to create and initialize an object created with a class and this must be unique within a particular class.
Super: Super is a keyword that is used to call the parent’s class method and data. It is used for the inheritance model of class.
Now let’s discuss why constructor and super in ReactJS are used and what their importance is.
- In ReactJS constructor is used for class components not for the functional component.
- It is used to initialize objects i.e, State in ReactJS.
- It is used to bind methods in ReactJS.
- It is used to read or access a parent’s property from a child’s component in ReactJS.
- There is no need for class until state variables are initialized based upon props.
- Constructor is essential whenever the need to access or generate local state.
- Constructor is used for binding event handlers that occur in components.
Note: Constructor runs before anything else in the class-based code in react.js to the life-cycle of the component.
Constructor code runs once, and only once, for the entire life-cycle of this component in react
- In ReactJS super call other constructor methods that is instantiated.
- In ReactJS, it is used to access parent properties and methods from the child components.
- It is used in an overridden method in react.js
- Super is reside always inside the constructor.
- Super is essential whenever the constructor is there in ReactJS.
- It is important to call super before the object initializes i.e, before using this.state in the constructor if it’s not there then the code gives a bug.
Let’s understand with the help of examples.
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:
Example: This file will run in the project structure of the file name App.js. The example describes how constructor is a method call and instantiates the object and the super is useful for this.state
Step to run the application: Open the terminal and type the following command.
Please Login to comment...