Created
June 17, 2016 15:43
-
-
Save tautologistics/70d933e03df82983782b017609aaa4ac to your computer and use it in GitHub Desktop.
Example react base component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BaseComponent extends Component { | |
constructor(props) { | |
super(props); | |
this.state = this._getState(props); | |
} | |
_shouldUpdateState() { return true; } | |
_getState(props) { | |
throw new Error('Method _getState needs to be defined in derived classes of BaseComponent'); | |
} | |
componentWillReceiveProps(nextProps) { | |
if this._shouldUpdateState(nextProps) { | |
this.setState(this._getState(nextProps)); | |
} | |
} | |
} | |
class MyComponent extends BaseComponent { | |
constructor(props) { | |
super(props); | |
} | |
_getState(props) { | |
return { | |
foo: props.foo || {}, | |
things: props.bar.map((item) => { return item.doodad; }) | |
}; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment