Override/extend static properties on ES7 classes in React.js
I stumbled upon this question, and it's been almost 3 years, but who know, someone might need it. (And it's still relevant)
Given that when you extend a class it automatically inherits of its parent class, you would not need to overwrite the static propTypes
property.
Given a parent class:
class Parent { static propTypes = { parentProp: PropTypes.string }}
If you don't want to add other propTypes/defaultProps, you can simply:
class Children extends Parent { // Do not declare the propTypes, it will extends by itself.}console.log(Children.propTypes); // Will output an object with parentProp in it
If you want to explicitly tell that you extends Parent
propTypes, or add new propTypes:
class Children extends Parent { static propTypes = { ...Parent.propTypes, // Yes, you can spread static properties like everything else childProp: Proptypes.number, }}
Small note, for this to work properly with Babel, you might need to include the transform-es2015-classes
babel plugin in your plugins or preset. My .babelrc
:
"presets": [ ["env", { "include": ["transform-es2015-classes"] }], "stage-0", "react"],
Hope this helps!
Curiously enough, using super
works for static methods. I'd think it should work for static properties too. To me, then, it feels more natural to use the super class name directly:
export default class ComponentTwo extends ComponentOne { static propTypes = _.merge({}, ComponentOne.propTypes, { baz: React.PropTypes.number });}
But, to use super
, one workaround I can think of is using a static method to initialize the property, which unfortunately would have to be called manually:
class ComponentTwo extends ComponentOne { static _init() { this.propTypes = _.merge({}, super.propTypes, { baz: React.PropTypes.number }); }}ComponentTwo._init();