Last active
April 24, 2018 02:29
-
-
Save cointilt/d4636a96f64186d3764205aad80a404f to your computer and use it in GitHub Desktop.
State Provider for Dumb Components
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
import React, { Component } from 'react' | |
import { bool, object } from 'prop-types' | |
class StateProvides extends Component { | |
state = { | |
state: {}, | |
hydrated: false, | |
} | |
static getDerivedStateFromProps(nextProps, prevState) { | |
// set up the default state value based on props, only the first time | |
// or if allowInitialStateUpdate is set | |
if (!prevState.hydrated || nextProps.allowInitialStateUpdate) { | |
return { | |
...prevState, | |
state: { | |
...previousState.state, | |
...nextProps.state, | |
}, | |
}, | |
hydrated: true, | |
} | |
} | |
return null | |
} | |
setState = (newState) => { | |
this.setState(s => ({ | |
state: { | |
...s.state, | |
...( | |
typeof newState === 'function' | |
? newState(s.state) | |
: newState | |
), | |
}, | |
})) | |
} | |
render() { | |
return this.children({ | |
state: this.state.state, | |
setState: this.setState, | |
}) | |
} | |
} | |
StateProvides.defaultProps = { | |
allowInitialStateUpdate: false, | |
state: {}, | |
} | |
StateProvides.propTypes = { | |
allowInitialStateupdate: bool, | |
state: object, | |
} | |
export default StateProvides |
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
import React from 'react' | |
import { string } from 'prop-types' | |
import StateProvides from './StateProvides' | |
const ReallyDumbComponent = ({ title }) => ( | |
<StateProvides state={{ show: false }}> | |
{({ state, setState }) => ( | |
<header> | |
<h2>{title} - {state.show && <span>hidden</span>}</h2> | |
<button | |
onClick={() => setState(s => ({ show: !s.show }))} | |
> | |
Toggle | |
</button> | |
</header> | |
)} | |
</StateProvides> | |
) | |
ReallyDumbComponent.propTypes = { | |
title: string.isRequired, | |
} | |
export default ReallyDumbComponent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment