Last active
July 23, 2018 09:32
-
-
Save dariocravero/2b3a9ec44997b1ed13a7b8c8496298e2 to your computer and use it in GitHub Desktop.
react-context
This file contains hidden or 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' | |
const ThemeContext = React.createContext({ | |
color: 'orange', | |
toggleColor() {}, | |
}) | |
class Theme extends React.Component { | |
state = { | |
color: 'orange', | |
toggleColor: () => { | |
this.setState({ | |
color: this.state.color === 'orange' ? 'purple' : 'orange', | |
}) | |
}, | |
} | |
render() { | |
return ( | |
<ThemeContext.Provider value={this.state}> | |
{this.props.children} | |
</ThemeContext.Provider> | |
) | |
} | |
} | |
const Button = props => ( | |
<ThemeContext.Consumer> | |
{({ color, toggleColor }) => ( | |
<button style={{ color }} onClick={toggleColor}> | |
{props.text} | |
</button> | |
)} | |
</ThemeContext.Consumer> | |
) | |
const App = () => ( | |
<Theme> | |
<Button text="hey!" /> | |
</Theme> | |
) |
This file contains hidden or 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 PropTypes from 'prop-types' | |
class Theme extends React.Component { | |
static childContextTypes = { | |
color: PropTypes.string, | |
toggleColor: PropTypes.func, | |
} | |
state = { | |
color: 'orange', | |
} | |
getChildContext() { | |
return { | |
color: this.state.color, | |
toggleColor: this.toggleColor, | |
} | |
} | |
toggleColor = () => { | |
this.setState({ | |
color: this.state.color === 'orange' ? 'purple' : 'orange', | |
}) | |
} | |
render() { | |
return this.props.children | |
} | |
} | |
const Button = (props, context) => ( | |
<button style={{ color: context.color }} onClick={context.toggleColor}> | |
{props.text} | |
</button> | |
) | |
Button.contextTypes = { | |
color: PropTypes.string, | |
toggleColor: PropTypes.func, | |
} | |
const App = () => ( | |
<Theme> | |
<Button text="hey!" /> | |
</Theme> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment