Subclassing React components

(Simon Harper) #1

I am in the process of writing a React application which is responsible for rending content from an external CMS.

Content is pulled from the CMS into a redux store when the application first loads and is accessed via connected components or props throughout its life-cycle.

I need certain methods to be available across all components making use of CMS’d content.

After researching the “React” way of achieving this, it seems the following way is generally frowned upon. Coming from an OO background, I’m struggling to understand why?

For example…

import React, { Component } from 'react';

class CMSComponent extends Component {

    constructor(props) {

    mySharedMethod(path) {
        // Assume CMS content is located in this.props.content unless otherwise stated
        // Please be aware that the actual code has been simplified massively for the sake of the question

        return this.props.content[path]

I now have a base class that all my CMS components can inherit from, like so…

import CMSComponent from './components/cms'

class Page1 extends CMSComponent {

    constructor(props) {

    render() {

        // mySharedMethod() inherited from base class

        return <div>{ this.mySharedMethod(['data', 'intl', 'my-keyed-content']) }</div>

If anyone could shed any light on why this isn’t considered correct I would be extremely grateful.

(Alexei) #2

Here is the great article related to this topic.
In your case, i suppose decorator pattern can be useful.

(Mickey Puri) #3

Hi @si-harps it doesn’t look like you got an answer, as the link on react simply said they “did not know of any use case”. I too have been asking myself this question and wondered if you had answered it.

The use case I see is if you want to put in place some common error handling to come in in case of an error.