I know in vanilla ES6 you can write a class
that extend
s a functional class. This is explained here.
React supports both ES6 class components, via extend
ing 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")
);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With