Skip to content

Instantly share code, notes, and snippets.

@idmontie
Created April 18, 2018 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idmontie/10328188d0bfeab174c3f720a869be62 to your computer and use it in GitHub Desktop.
Save idmontie/10328188d0bfeab174c3f720a869be62 to your computer and use it in GitHub Desktop.
export default class Toggle extends Component {
static TOGGLE = 'TOGGLE';
state = { on: false }
onClick = (e) => {
e.preventDefault();
this.internalSetState(state => ({
on: !state.on,
type: this.constructor.TOGGLE,
}));
}
internalSetState(changes, callback) {
this.setState(state => {
const stateToSet = [changes]
// handle function setState call
.map(c => (typeof c === 'function' ? c(state) : c))
// apply state reducer
.map(c => this.props.stateReducer ? this.props.stateReducer(state, c) : c)
// remove the type so it's not set into state
.map(({ type: ignoredType, ...c }) => c)[0];
return stateToSet;
}, callback);
}
render() {
return this.props.children({
...this.state,
onToggle: this.onClick,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment