Open In App

What is Components Inheritance in React ?

Last Updated : 17 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In React, Component Inheritance refers to one component inheriting the behaviors of another component. It allows objects to have those properties that already exist on previous or parent objects. It is a concept that plays a major role in object-oriented programming.

Two classes exist for Component Inheritance in React are:

  • Superclass(Parent Class Component)
  • Subclass(Child Class Component)

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.

Steps to Create React Application:

Step 1: Create a React application using the following command in the terminal/ command prompt:

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:

Project Structure

Example: This example implements component inheritance by rendering a message in the ChildComponent passed from the Parent component.

Javascript




// Filename  - App.js
 
import React from "react";
import "./App.css";
import ChildComponent from "./ChildComponent";
 
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            message: " Geeks for Geeks message",
        };
    }
 
    render() {
        return (
            <div>
                <ChildComponent
                    message={this.state.message}
                />
            </div>
        );
    }
}
export default App;


Javascript




// Filename - ChildComponent.js
 
import React from "react";
 
class ChildComponent extends React.Component {
    render() {
        const { message } = this.props;
        return (
            <div>
                <p>
                    {" "}
                    Message from App component :{" "}
                    <b>{message}</b>{" "}
                </p>
            </div>
        );
    }
}
 
export default ChildComponent;


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

npm start

Output: This output will be visible on the http://localhost:3000/ on the browser window.

Child Component accessed App component properties



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads