Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React class methods overriding

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?

like image 806
Alex Berdyshev Avatar asked Jan 26 '16 00:01

Alex Berdyshev


1 Answers

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.

like image 155
David L. Walsh Avatar answered Oct 04 '22 06:10

David L. Walsh