Subclassing react components, HOC or classic OO?

639 views Asked by At

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 whilst using higher order components is viewed as a better practice. Coming from an OO background, I'm struggling to understand why?

For example...

import React, { Component } from 'react';

class CMSComponent extends Component {

    constructor(props) {
        super(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) {
        super(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 is considered incorrect I would be extremely grateful.

For reference, I guess the same scenario using HOC would look something like this...

import React, { Component } from 'react'

export default function CMSInject(ChildComponent) {

    class CMSComponent extends Component {

        constructor(props) {
            super(props);       
        }

        mySharedMethod(path) {
            return this.props.content[path]
        }

        render() {

            return <ChildComponent {...this.props} {...this.state} /* and some refs */ />
        }
    }

    return CMSComponent
}

...then export the child via the higher order parent component...

import React, { Component } from 'react'

class Page1 extends Component {

    constructor(props) {
        super(props);       
    }

    render() {

        // mySharedMethod() still inherited from base HOC class

        return <div>/* CMS BASED CONENT HERE */</div>
    }
}

export default CMSInject(Page1)
0

There are 0 answers