Best Practices for Extending/Subclassing Components?

(Con Antonakos) #1

Is there a way to efficiently extend components/created classes to other components. For example, I have a component (first component) with a certain HTML structure, but I want to iterate and change it slightly for another component (second component) that shares every other aspect of that first component except for the slightly different render function.

I want to do something akin to this:

var SecondComponent = FirstComponent;
SecondComponent.prototype.render = function(){ ... };

Thanks in advance!

EDIT: Actually, I think this may have worked, but I guess I’d love to read other opinions on this.

EDIT #2: This doesn’t work entirely. The FirstComponent gets assigned a reference to the SecondComponent, and any changes to the prototype of the Second affect the First.

(Sophie Alpert) #2

Your code example modifies FirstComponent and is unlikely to be what you want. We suggest instead using composition, like

var PurpleComponent = React.createClass({
  render: function() {
    render <FirstComponent {...this.props} color="purple" />;

or similar. Depending on your particular code structure, you may need to extract the common pieces out into a third component, but this is almost always easier to reason about and easier to maintain than subclassing. (If that example isn’t clear, I can try to give more specific suggestions if you post more details about your use case.)

(Theadd) #3

Just adding some related resources to this topic.

Use composition over inheritance

The following post by @gaearon exposes one way to solve your problem using composition:
Mixins Are Dead. Long Live Composition

Operating on the DOM nodes may also be tricky because the wrapper component has no way to know when the child’s state updates. You can solve this by providing a callback ref (new in React 0.13) as one of the props to the composed component. It can then use ref={this.props.someRef} to notify the higher-order component about attaching and detaching a particular DOM node. The higher-order component can then use React.findDOMNode to work with that node.

If the code of your component is not long, it might be clearer if you just make a copy of it to a new one + changes.

Finally, if you’re doing some dirty things you can make use of this function to clone a third object(s) containing all shared stuff (even getters/setters) and assign those clones to your components. But this last one does not seem to be the proper way to do things. Its not even a clear way.

(Mazong1123) #4

Be honestly, I don’t like HoC. So I just implemented reactOO , which let you write react component in a REAL OO way.

Now it’s much more easier to use ReactJS in an OO way:

window.ButtonClass = window.ReactOO.ReactBase.extend({
        getReactDisplayName: function () {
            return 'Button';

        onReactRender: function (reactInstance) {
            var self = this;

            var text = reactInstance.props.text;

            return React.createElement('button', self.getButtonProperty(reactInstance), text);

        getButtonProperty: function (reactInstance) {
            return {};

    var button = new window.ButtonClass();
    button.render({ text: 'Button' }, '#normalButton');

Let’s say we want a richer button, just overrides the getButtonProperty:

window.StyledButtonClass = window.ButtonClass.extend({
        getReactDisplayName: function () {
            return 'StyledButton';

        getButtonProperty: function (reactInstance) {
            var self = this;
            var property = self._super();

            property.className = 'nice-button';

            return property;

    var styledButton = new window.StyledButtonClass();
    styledButton.render({ text: 'Styled Button' }, '#styledButton');

    window.StyledButtonWithClickHandlerClass = window.StyledButtonClass.extend({
        getReactDisplayName: function () {
            return 'StyledButtonWithClickHandler';

        getButtonProperty: function (reactInstance) {
            var self = this;
            var property = self._super();

            property.onClick = reactInstance.handleClick;

            return property;

        onReactHandleClick: function (reactInstance, e) {


    var styledButtonWithClickHandler = new window.StyledButtonWithClickHandlerClass();
    styledButtonWithClickHandler.render({ text: 'Styled Button With Click Handler' }, '#styledButtonWithClickHandler');

I know Facebook recommends HoC. I just put my thoughts here as an old-school OO guy.

(Cauburtin) #5

advantage of HoC is multiple ‘inheritance’

(hanamant jimmannavar) #6


i want to access functions of other component by creating sub class
is it possible in react js…?somthing like below

var comp1=React.createClass({


var comp2 extends comp1({


note: comp2 is not child of comp1

(Gboyega) #8

This is what brought me here. I’m new to react (and redux) and I thought extending a component (especially in the ES6 way) would let the new component inherit methods and properties of it’s parent (or at least something!) Composition is all well and good but why make it the only way?

(Borisyankov) #9

OO has been promoted too long as the only viable approach, while it is just one of many.
You don’t need to inherit to reuse.

@gboyega Why do you need to inherit methods of any component?
What is your specific use case, and we can tell you how to implement.

(Gboyega) #10

Hello @borisyankov, I am doing my first website project with react and redux. I have the react-router added and I have mapped a few paths to different components (one for each page). They all need to fetch json content when loaded and they have to display a spinner while loading. I also have a menu for mobile devices that will slide out when you click a button. I need it to slide back when we navigate to a page. This works when I use componentDidMount in each page component. But I wanted this function as well as the loading mechanism (that will do a get request to the appropriate endpoint) to be in a base component called “Page” that all page components simply extend. I am using es6 and the syntax for creating react components gave the impression that I could also extend my own component “classes” but I guess I am starting to see they are not meant to be classes in the OO sense.

(Borisyankov) #11

In React, composition is so natural that it is often transparent at first sight.

Wat you can do is something like:

  <SomeComponent />

Your Page component will have the common code, while your SomeComponent will differ from page to page.

Also, extract the logic for getting the data from server in a Container component, that will do just that, and then on render will return another component that is purely presentational, it will have no idea where the data comes from.

(Talin) #12

Despite what’s been said here, there are occasions where inheritance really is the right answer - so how do you make it work?

(Sven van de Scheur) #13

@viridia I’m not quite sure if you still need an answer but I also noticed that sometimes inheritance is the anwer. I also noticed that quite ofter when you mention it the reply is that you should use composition, which is valid… to some extend…

The use cases for inheritance and composition are different. When you want to arrange a hierarchy of components composition will do just fine. But if those components are practically the same as other components abstraction (inheritance) might still be useful.

I’m working on a project right now that uses both composition and inheritance, or even composition using inherited components. I noticed little problems when using es6 class X extends Y where class Y extends React.Component. I didn’t find actual issues (not even with DOM updates). I think this is because class X becomes LIKE class Y, but not equal to class Y.

There is one thing you should be aware of, the constructor method…

The constructor method gets fired once, and you should NOT use it to set props to the this context. THIS WILL BECOME AN ISSUE. This is because if you bind to those derived properties in the this context. You will bind to data that gets never updated again.

A solution to this problem might be using es6 getters. Getter are properties that behave like methods. You will be able to attach them directly to the this context (getters are attached even before the constructor, this might need some protective programming) and use them to obtain data derived for you properties.

Example (returns last item from array or 0)

get currentValue() {
    return[ - 1] || 0;

This will work around the constructor issue because every time the property currentValue is accessed the attached method looks again for the correct output resulting in a WORKING potentialDOM update

(Troy Rhinehart) #14

If you simply need all the react lifecycle events of FirstComponent but want to render something differently then simply extend it.

class SecondComponent extends FirstComponent {
  render () {

or if you want to have your own lifecycle events and then pass them as props to FirstComponent create a higher order component.

function Hoc (Component) {
  return class Wrapped extends React.Component {
    constructor () {
      this.state = { ... }
    render () {
      return <Component { ...this.props } { ...this.state } />
const SecondComponent = Hoc(FirstComponent);

(Haslayout) #15

I have a question about the HOC way to extending component.
Just like @spicyj mentioned, we can use composition:

var PurpleComponent = React.createClass({
render: function() {
render <FirstComponent {…this.props} color=“purple” />;

But the problem is that if the `FirstComponent` doesn't have `color` props, I have to make `FirstComponent` support `color`, so I have to modify `FirstComponent`. And the `HOC` seems useless here.

(Kevin Suttle) #16

I have run into the same issue. When you want to modify the original component, you seem forced to write a wrapper.

(Dirk Roorda) #17

There is a third case: FirstComponent is is stateful and must be wrapped by a component that saves the state of FirstComponent when it unmounts. And it must initialize the state of FirstComponent when FirstComponent is created. How can you do this by composition? My biggest problem is how to write the constructor() of the wrapper.

(Nikolas) #18

I think you meant return <FirstComponent {...this.props} color="purple" />; instead of render <FirstComponent {...this.props} color="purple" />;

(Mikayel) #19

I think this kind of questions start appearing more when react decided to use “extends” syntax in most help documents. See below.
class HelloMessage extends React.Component {
render() {

Hello {}
ReactDOM.render(, mountNode);

instead of this
var HelloMessage = React.createClass({ …

What was the main reason to move to the new syntax? Why they make beginners life so difficult? And competitors are using that to show everyone that react has difficult syntax…

(Nelsie Borja) #21

Very informative video for creating HOC

(Rael Gugelmin Cunha) #22

Of course inheritance is the most natural way to work while extending a class. But when people say you MUST use composition (or related excuses), it’s because the framework/language doesn’t work properly with inheritance. Which is the case of React.