I am trying to create some kind of class composition in react:
class Entity {
constructor(props) {
super(props);
}
renderPartial() {
return (<div>Entity</div>)
}
render() {
return (<div>header {this.renderPartial()}</div>);
}
}
class Person extends Entity{
constructor(props) {
super(props);
}
renderPartial() {
return (<div>Person</div>)
}
}
class Manager extends Person {
constructor(props) {
super(props);
}
renderPartial() {
return (<div>Manager</div>)
}
}
In the following example Person
extends from Entity
class. And the goal here is to render partial content inside of the extended class. So for the simplicity sake I just render class name. This way everything works fine with Person class and it renders its text. But when I extend Manager from Person it writes <div>Person</div>
and I can't understand why. Is there any way to override renderPartial
inside of the Manager
class?
Don't use inheritance in React (other than extending React.Component
). It's not the recommended approach. More on this here. (See also here.)
If you need outer and inner components, you can use this.props.children
. e.g.
render() {
return <div>header {this.props.children}</div>;
}
This allows you to do the following:
<Entity>
<Person />
</Entity>
But usually even this is unnecessary. Simply split your components into smaller pieces. e.g.
<div>
<Header />
<Person />
</div>
Small, modular components are much easier to manage than gargantuan objects with long inheritance chains.
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