Created
June 27, 2018 16:50
-
-
Save slorber/c9deabe31bb831e7dc17204a1db35f6b 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
import React from 'react'; | |
// Permit to create a provider/consumer but allow the consumer | |
// to also receive a setter to update the provider value | |
export const createUpdatableContext = () => { | |
const { Provider, Consumer } = React.createContext(null); | |
class UpdatableContextProvider extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
realValue: props.value, | |
setter: value => { | |
this.setState({ realValue: value }); | |
}, | |
}; | |
} | |
render() { | |
return <Provider value={this.state}>{this.props.children}</Provider>; | |
} | |
} | |
class UpdatableContextConsumer extends React.Component { | |
render() { | |
return ( | |
<Consumer> | |
{value => this.props.children(value.realValue, value.setter)} | |
</Consumer> | |
); | |
} | |
} | |
return { | |
Provider: UpdatableContextProvider, | |
Consumer: UpdatableContextConsumer, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment