Inherit defaultProps from superclass in React

I think some props

(like theme) are so versatile among components that it makes sense to extract their handling (into a superclass). Then it follows that their default value also belongs.

However, what would be the idiotic way to achieve this in React?

class Base extends React.Component {
  bgColor() {
    switch (this.props.theme) {
      case 'Summer': return 'yellow'; break;
      case 'Autumn': return 'grey'; break;
      case 'Winter': return 'white'; break;
    }
  }
}
Base.defaultProps = {
  theme: 'autumn'
};

      


class Sky extends Base {
  render() {
    return <div style={{backgroundColor: this.bgColor()}}>{this.props.clouds}</div>;
  }
}
Sky.defaultProps = {
  clouds: []
};

      

... defaultProps

is a property of a class (as opposed to an instance) and there is no inheritance.

+3


source to share


1 answer


By assigning Sky.defaultProps

, you hide the base. If you want to combine them, you need to explicitly do so, eg.



Sky.defaultProps = Object.assign({}, Base.defaultProps, {
  clouds: []
});

      

+6


source







All Articles