What is Components Inheritance in React ?
Inheritance is a concept that plays a major role in object-oriented programming. It is a technique that allows objects to have those properties that are already existing on previous objects.
Two classes exist are:
- Superclass(Parent Class)
- Subclass(Child Class)
In React, the composition model is used instead of inheritance, so that code can be re-used again between the components. In react extends keyword is used on the main function i.e the constructor function. By using the extends keyword you can have the present component have all the component properties from the already existing component. The composition model uses the super-sub class relationship by passing the state and props. The sub-class segment can access any progressions to one another.
Creating React Application:
Step 1: Create a React application using the following command in the terminal/ command prompt:
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
Project Structure: It will look like the following:
Here, you have two components i.e. AppComponent and a ChildComponent, and the child component takes over all the app properties.
Example: Now write down the following code in the App.js file. Here, App is our default(parent) component where we have written our code. In the below code, this.state.message is passed to ChildComponent.
Now write down the following code in the ChildComponent.js file. The child component accepts all the app component properties.
Step to Run Application: Run the application using the following command from the root directory of the project: