9
votes

I know in vanilla ES6 you can write a class that extends a functional class. This is explained here.

React supports both ES6 class components, via extending React.Component, and functional components. I'm getting the following error when attempting to extend a functional component, though.

TypeError: Cannot call a class as a function

I'm trying to write some code that extends a component and works for both ES6 class components and functional components. I want to write a function that returns a component, but instead of a higher order component I just want to extend and modify some props.

Below is some example code that I've tried and does not work. Is this possible? I realize the BarExtended would not render Bar at all, but I was just testing. Unless this is part of the issue.

function Bar() {
    return (
    <h1>Bar</h1>
  );
}

class BarExtended extends Bar {
    render() {
    return (
        <h1>BarExtended</h1>
    );
  }
}

ReactDOM.render(
    <div>
    <BarExtended />
    </div>,
  document.getElementById("foo")
);
2
React recommends composition over inheritance. Functions can be composed easily so if you ditch the inheritance, your problem goes away.Mulan

2 Answers

3
votes

Warning this isn't really possible at least to my knowledge to do in terms of react though because you need to inherit from React.Component to make it a react component like so bar is just a function.

class Bar extends React.Component {

}

You don't have to use classes with react you can use regular functions. But I think what you are looking for is Higher Order Components. Which can give you extra functionality to any components that you pass to it.

function Bar(WrappedComponent){
 return class BarExtended extends React.Component {
  addThisFunction(){
    console.log('I extended the wrapped component with functionality')
  }
  render (
    return (
     <WrappedComponent addThisFunction={this.addThisFunction}/>
    )
  )
 }
}

You can do this if you really want from regular classes though. This is right from the classes documentation.

function Animal (name) {
  this.name = name;  
}

Animal.prototype.speak = function () {
  console.log(this.name + ' makes a noise.');
}

class Dog extends Animal {
  speak() {
    console.log(this.name + ' barks.');
  }
}

var d = new Dog('Mitzie');
d.speak();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

-1
votes

Um.. I think it doesn't make sense at all.

A functional component is just a function, you know, a render function.
So extending a functional component means you will override the render function, and.. it means that you override the entire functional component (because it's just a render function), then you extend nothing.