Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use inheritance with React components and es6 classes

I'm attempting to subclass a React component, and my overridden methods aren't being called:

class Foo extends React.Component {
  someMethod() { ... }

  render() {
    return <div>{this.someMethod()}</div>;
  }
}

class Bar extends Foo {
  someMethod() {
    // Never gets called
  }
}

In fact, when I render a <Bar /> in my DOM and look at the component in the debugger, it shows the component type as 'Foo'.

(Also, please note that I'm familiar with all of the arguments about composition vs. inheritance. Trust me, inheritance really is the right answer for my specific use case, so let's not start that argument.)

(Also, I know about potential duplicate issue #27233491, but the solutions given there don't actually seem to work for me.)

Update:

I see @Aaron's example on CodePen showing how this works, but I'm seeing different behavior in my app. Specifically:

class Foo extends React.Component {
  render() {
    console.log(this); // Always prints 'Foo...'.
    return <div></div>
  }
}

class Bar extends Foo {
  render() {
    console.log(this); // Always prints 'Bar...'.
    return super.render();
  }
}

What I see on the dev console when I render Bar is:

> Bar { props: ...etc. }
> Foo { props: ...etc. }

In other words, the first logging statement prints 'this' as being of type Bar, and the second one prints 'this' as being type Foo. Both from the same render() call.

like image 826
Talin Avatar asked Oct 18 '22 09:10

Talin


1 Answers

Found the problem: I was using withRouter() on the base class. You can't inherit from a HoC, it treats all of the methods as though .bind(this) had been called on them.

like image 141
Talin Avatar answered Oct 21 '22 05:10

Talin