5

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.

6
  • What is someMethod and what are you expecting to call it? Commented May 17, 2016 at 17:03
  • It's being called during render(). I'll update my example. Commented May 17, 2016 at 17:24
  • 1
    This is working on CodePen. Commented May 17, 2016 at 17:46
  • You should definitely read Correct way to inherit React components Commented May 17, 2016 at 18:30
  • @FelixKling Did already, thanks :) Commented May 17, 2016 at 18:56

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.