Created
April 18, 2018 00:08
-
-
Save idmontie/10328188d0bfeab174c3f720a869be62 to your computer and use it in GitHub Desktop.
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
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