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:
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:
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.
App.js
import logo from './logo.svg' ; 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; |
Now write down the following code in the ChildComponent.js file. The child component accepts all the app component properties.
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: