Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  20] [ 7]  / answers: 1 / hits: 27412  / 9 Years ago, tue, january 26, 2016, 12:00:00

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?


More From » reactjs

 Answers
8

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.


[#63562] Saturday, January 23, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevenirvina

Total Points: 315
Total Questions: 112
Total Answers: 84

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
;