Skip to content

Instantly share code, notes, and snippets.

@cointilt
Last active April 24, 2018 02:29
Show Gist options
  • Save cointilt/d4636a96f64186d3764205aad80a404f to your computer and use it in GitHub Desktop.
Save cointilt/d4636a96f64186d3764205aad80a404f to your computer and use it in GitHub Desktop.
State Provider for Dumb Components
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
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