Author avatar

Gaurav Singhal

React.js and Inheritance

Gaurav Singhal

  • Nov 10, 2020
  • 6 Min read
  • 113 Views
  • Nov 10, 2020
  • 6 Min read
  • 113 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

Code reusability is an impactful aspect in any component-based library or a framework. React provides the composition and inheritance for code reusability. Inheritance is used to couple components and their properties, which allows an app to implement code sharing between the components.

This guide provides an overview of how to implement inheritance and see the composition model usage.

What is Inheritance?

Inheritance is a way to achieve code reusability when some objects have the same number of properties that can be shared across the app. Inheritance allows the app to do the coupling between the parent-child component and reuse properties such as state values and function in its child components.

React does not use inheritance except in the initial component class, which extends from the react package.

Implement Inheritance in React

Inheritance uses the keyword extends to allow any component to use the properties and methods of another component connected with the parent. Using the extends keyword, you can allow the current component to access all the component's properties, including the function, and trigger it from the child component.

This example creates one component called ParentClass.jsx.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from "react";

class ParentClass extends React.Component {
  constructor(props) {
    super(props);
    this.callMe = this.callMe.bind(this);
  }

  // ParentClass function
  callMe() {
    console.log("This is a method from parent class");
  }

  render() {
    return false;
  }
}
jsx

ParentClass extends the component from React as React.component, which means the newly created component itself is using the inheritance. After creating parent class/component, create one child component, Example.jsx.

1
2
3
4
5
6
7
8
9
export default class Example extends ParentClass {
  constructor() {
    super();
  }
  render() {
    this.callMe();
    return false;
  }
}
jsx

The Example class extends ParentClass so the child class will access all the properties and methods created inside the parent component.

1
2
3
4
render() {
  this.callMe();
  return false;
}
jsx

Here in the child class, the this.callMe() function is called the part of parent class implementation, so the parent component's properties and its methods can be accessed by implementing inheritance in the child component.

Using Composition in React

As per the official React documentation:

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components

Compared to the inheritance, the composition model is much more robust and less coupled because it does inheritance but doesn't extend the classes directly.

The composition model uses the parent-child relationship by passing the state, props, and function to the child component as a prop's value. The child component can access or trigger any changes to each other. For example, you have two-component ParentComponent and a ChildComponent, and the parent's properties get consumed in the child component.

Now create one file called ParentComponent.jsx.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from "react";
import ChildComponent from "./ChildComponent";

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            message: "This is a message from parent class"
        };
    }

    render() {
        return (
            <div>
                <ChildComponent message={this.state.message} />
            </div>
        );
    }
}

export default ParentComponent;
jsx

From the parent component, the value this.state.message is passed to the child component without extending any component.

Create one file called ChildComponent.jsx.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from "react";

class ChildComponent extends React.Component {
    render() {
        const { message } = this.props;
        return (
            <div>
                <p>
                    Message from Parent component : <b>{message}</b>
                </p>
            </div>
        );
    }
}

export default ChildComponent;
jsx

The child component accesses the parent component's property called message without extending the ParentComponent.

In the same way, any function can also be triggered by the child component .

1
2
3
clickMe() {
    console.log("Action triggered from child component");
}
jsx

And pass it to the child component.

1
2
3
4
5
6
7
render() {
    return (
        <div>
            <ChildComponent message={this.state.message} clickMe={this.clickMe} />
        </div>
    );
}
jsx

The function gets accessed as a prop from the child component and can also get triggered as below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from "react";

class ChildComponent extends React.Component {
    render() {
        const { message } = this.props;
        return (
            <div>
                <p>
                    Message from Parent component : <b>{message}</b>
                </p>
                <button onClick={this.props.clickMe}>Click Me</button>
            </div>
        );
    }
}

export default ChildComponent;
jsx

The function clickMe() is triggered by the button click event, and the parent component will process the event.

1
<button onClick={this.props.clickMe}>Click Me</button>
jsx

The composition model allows you to restrict code overuse and decouple components, which can not be possible with inheritance because it needs all the components in sequence. It may lead to code overuse or decomposition at any given point in time.

Conclusion

React uses inheritance to initialize class as a component. Apart from that, there is no use to suggest to implement component inheritance chaining.

Instead, the composition model is used to manage the props and function communication and maintain code reusability. You can always use a composition pattern to avoid shared logic behavior.

If you have any queries, feel free to ask at Codealphabet.

2