Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active August 24, 2017 04:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/33a17e88786b18fb668855364fb09514 to your computer and use it in GitHub Desktop.
Save ryanflorence/33a17e88786b18fb668855364fb09514 to your computer and use it in GitHub Desktop.
// how I share state anywhere in the tree
<Route render={({ match: { params } }) => ()}/>
<Geolocation>
{coords => ()}
</Geolocation>
<FirebaseRef path="/somewhere">
{(doc) => ()}
</FirebaseRef>
<Forecast onData={(forecast) => {}}/>
<Forecast coords={coords}>
{forecast => ()}
</Forecast>
<Fetch url="/somewhere" onLoad={(data) => {}}/>
<Fetch url="/somewhere">
{data => ()}
</Fetch>
<UserPrefs>
{prefs => ()}
</UserPrefs>
// AND NOW YOU GET COMPOSITION EXPLOSION!
<Route path="/forecast/:days" render={({ match: { params }}) => (
<UserPrefs>
{prefs => (
<Geolocation>
{(coords) => (
<Forecast coords={coords} days={params.days}>
{forecast => (
<ul>
{forecast.days.map(day => (
<li>{ICONS[prefs.iconset][day.icon]}</li>
))}
</ul>
)}
</Forecast>
)}
</Geolocation>
)}
</UserPrefs>
)}/>
// "EW GROSS"
// wrap it up
const LocalForecast = ({ children, days }) => (
<Geolocation>
{(coords) => (
<Forecast coords={coords} days={days}>
{forecast => (
children(forecast)
)}
</Forecast>
)}
</Geolocation>
)
// Better?
<Route path="/forecast/:days" render={({ match: { params }}) => (
<UserPrefs>
{prefs => (
<LocalForecast days={params.days}>
{forecast => (
<ul>
{forecast.days.map(day => (
<li>{ICONS[prefs.iconset][day.icon]}</li>
))}
</ul>
)}
</LocalForecast>
)}
</UserPrefs>
)}/>
// Still unhappy? Wrap it up some more
const ForecastIcons = ({ days }) => (
<UserPrefs>
{prefs => (
<LocalForecast days={days}>
{forecast => (
<ul>
{forecast.days.map(day => (
<li>{ICONS[prefs.iconset][day.icon]}</li>
))}
</ul>
)}
</LocalForecast>
)}
</UserPrefs>
)
// How's that?
<Route path="/forecast/:days" render={({ match: { params }}) => (
<ForecastIcons days={params.days}/>
)}/>
// anybody in the tree anywhere who needs the forecast:
<Forecast>
{forecast => ()}
</Forecast>
// or the user prefs
<UserPrefs>
{prefs => ()}
</UserPrefs>
// These components are basically: connect(mapStateToProps) + reducer
// that can give you shared state access deeply w/o passing props 80 times.
// mutations can come in as a function too
<UserPrefs>
{({ prefs, updatePref }) => (
<button onClick={() => {
updatePref('food', 'tacos')
}}>Prefer tacos</button>
)}
</UserPrefs>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment