Posted by on in iDevelop, Javascript | 0 comments

People like me who come from the typical Object Oriented background coming from PHP, Java, C# etc would say yes, code inheritance is a good practice. But what do you do when you are working with a language which does not follow your typical OO paradigms?! Yes, I’m talking about Javascript – the language people like to love and hate at the same time. And on top of that, you happen to be working with React, it becomes an altogether different matter.

Javascript does not have the same code inheritance concept as something like PHP or Java etc. Sure, ES6 introduced classes in Javascript and while that did make writing code for someone like me easier, if you look at it, its just syntactical sugar. Almost all modern browsers support ES6 at present and for that matter even ES7, ES8 & ES9. Yet, we use Babel to transpile the code back to JS basics away from the neat & clean looking syntactical sugar.

Basic rule to indulge in code inheritance is to be able to reuse code and keep things clean and better organised. So we can do this:

  1. class Vehicle {
  2.  
  3.     protected string $_type        = '';
  4.     protected string $_maker       = '';
  5.     protected string $_model       = '';
  6.     protected string $_colour      = '';
  7.     protected bool $_is_amphibious = false;
  8.  
  9.     public function __construct() {}
  10.  
  11.     public function get_type() : string {
  12.         return $this->_type;
  13.     }
  14.  
  15.     public function get_maker() : string {
  16.         return $this->_maker;
  17.     }
  18.  
  19.     public function get_model() : string {
  20.         return $this->_model;
  21.     }
  22.  
  23.     public function get_colour() : string {
  24.         return $this->_colour;
  25.     }
  26.  
  27.     public function is_amphibious() : bool {
  28.         return $this->_is_amphibious;
  29.     }
  30.  
  31. }
  32.  
  33. class Car extends Vehicle {
  34.  
  35.     protected string $_type        = 'car';
  36.     protected bool $_is_amphibious = false;
  37.  
  38.     public function __construct( string $maker, string $model, string $colour ) {
  39.         $this->_maker  = $maker;
  40.         $this->_model  = $model;
  41.         $this->_colour = $colour;
  42.     }
  43.  
  44. }
  45.  
  46. $lambo = new Car(
  47.     'Lamborghini',
  48.     'Huracan Evo Spyder',
  49.     'Verde Selvans'
  50. );
  51.  
  52. printf(
  53.     'The car is %s from %s in %s colour and it looks fabulous.',
  54.     $lambo->get_model(),
  55.     $lambo->get_maker(),
  56.     $lambo->get_colour(),
  57. );

It looks right here however different languages have their own take of code reusability. For instance, since this is PHP code, I might instead go with this version of it:

  1. trait Vehicle {
  2.  
  3.     protected string $_type        = '';
  4.     protected string $_maker       = '';
  5.     protected string $_model       = '';
  6.     protected string $_colour      = '';
  7.     protected bool $_is_amphibious = false;
  8.  
  9.     public function get_type() : string {
  10.         return $this->_type;
  11.     }
  12.  
  13.     public function get_maker() : string {
  14.         return $this->_maker;
  15.     }
  16.  
  17.     public function get_model() : string {
  18.         return $this->_model;
  19.     }
  20.  
  21.     public function get_colour() : string {
  22.         return $this->_colour;
  23.     }
  24.  
  25.     public function is_amphibious() : bool {
  26.         return $this->_is_amphibious;
  27.     }
  28.  
  29. }
  30.  
  31. class Car {
  32.  
  33.     use Vehicle;
  34.  
  35.     public function __construct( string $maker, string $model, string $colour ) {
  36.  
  37.         $this->_type          = 'car';
  38.         $this->_is_amphibious = false;
  39.  
  40.         $this->_maker  = $maker;
  41.         $this->_model  = $model;
  42.         $this->_colour = $colour;
  43.  
  44.     }
  45.  
  46. }
  47.  
  48. $lambo = new Car(
  49.     'Lamborghini',
  50.     'Huracan Evo Spyder',
  51.     'Verde Selvans'
  52. );
  53.  
  54. printf(
  55.     'The car is %s from %s in %s colour and it looks fabulous.',
  56.     $lambo->get_model(),
  57.     $lambo->get_maker(),
  58.     $lambo->get_colour(),
  59. );

It would get me the same result but more importantly, the Car would be free to inherit another class. Class inheritance in PHP is a very expensive commodity in the sense that there can only be a single parent.

Now coming back to Javascript & React – class inheritance is available ES6 onwards in a similar way, as far as syntax is concerned. But when you’re making React components, do you really need it?!

Last night while I was working on refactoring some code on a pet project, I was sort of in a bind. ( I’m new to React at the moment. ) I had this JSX for displaying messages and I wanted to make it more re-usable and have cleaner implementation. So I started out with creating a base MessageDisplay component and my first thought was, should I extend this to specific components to display specific messages based on the context! And then I realised I don’t need to actually do that. And so this is what I ended up doing:

javascript
components/MessageDisplay.js

  1. import React from 'react';
  2.  
  3. export default class MessageDisplay extends React.Component {
  4.  
  5.     constructor( props ) {
  6.         super( props );
  7.  
  8.         this.setVars();
  9.     }
  10.  
  11.     setVars = () => {
  12.         this.type = this.props.type;
  13.     };
  14.  
  15.     render() {
  16.  
  17.         if ( ! React.isValidElement( this.props.messageJsx ) ) {
  18.             return null;
  19.         }
  20.  
  21.         return (
  22.             <div className={`message ${this.type}`}>
  23.                 {this.props.messageJsx}
  24.             </div>
  25.         );
  26.  
  27.     }
  28.  
  29. }
javascript
…nts/SuccessMessageDisplay.js

  1. import React from 'react';
  2. import MessageDisplay from './MessageDisplay';
  3.  
  4. export default class SuccessMessageDisplay extends React.Component {
  5.  
  6.     constructor( props ) {
  7.         super( props );
  8.  
  9.         this.setVars();
  10.     }
  11.  
  12.     setVars = () => {
  13.         this.type = 'success';
  14.         this.messageJsx = this.props.messageJsx;
  15.     };
  16.  
  17.     render() {
  18.  
  19.         return (
  20.             <MessageDisplay
  21.                 type={this.type}
  22.                 messageJsx={this.messageJsx}
  23.             />
  24.         );
  25.  
  26.     }
  27.  
  28. }

Now to display a success message, all I had to do was this:

javascript

  1. import React from 'react';
  2. import SuccessMessageDisplay from './SuccessMessageDisplay';
  3.  
  4. export default class MyComponent extends React.Component {
  5.  
  6.     constructor( props ) {
  7.         super( props );
  8.     }
  9.  
  10.     getMessageJsx = () => {
  11.  
  12.         return (
  13.             <>
  14.                 <div className="header">Congrats!</div>
  15.                 <div className="content">
  16.                     This is a success message displaying on
  17.                     your screen successfully!
  18.                 </div>
  19.             </>
  20.         );
  21.  
  22.     };
  23.  
  24.     render() {
  25.  
  26.         return (
  27.             <>
  28.                 <div className="top box">
  29.                     <SuccessMessageDisplay
  30.                         messageJsx={this.getMessageJsx()}
  31.                     />
  32.                 </div>
  33.                 <div className="content box">
  34.                     Some content and UI to be displayed here.
  35.                 </div>
  36.             </>
  37.         );
  38.  
  39.     }
  40.  
  41. }

And then the light in my brain turned on and told me to refer to React docs and see if there is any suggestion there on this topic. Turns out there is a React doc on Composition vs Inheritance! It explains it quite well with code examples on why inheritance is actually not needed in React components.

Sure, in above example I could’ve extended MessageDisplay in SuccessMessageDisplay and worked with that and that would have worked ( like this ). But there is no good reason to do it. Just because we can do something does not mean it should be done. Keeping both MessageDisplay and SuccessMessageDisplay as separate components works just as well, allows for code-reuse and keeps the code neat and organised.

Its something similar to the PHP Traits – they are about code reusability without implementing the parent-child relationship between classes and I’m glad that the Traits were added in PHP instead of class inheritance being updated to allow for multiple parents. Having something like Traits opened up other possibilities and gives a lot of flexibility in how you arrange and manage your code while keeping the basic principle of code reusability in effect. Same way React’s Composition allows for more flexibility in the code and encourages code reusability without having to resort to funky code in components trying to make them work with inheritance.