Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an ES6 class React Component that extends a functional component?

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")
);
like image 943
Ryan Avatar asked Jan 12 '17 02:01

Ryan


1 Answers

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

like image 145
Enjayy Avatar answered Sep 23 '22 19:09

Enjayy