Skip to content

Instantly share code, notes, and snippets.

@dariocravero
Last active July 23, 2018 09:32
Show Gist options
  • Save dariocravero/2b3a9ec44997b1ed13a7b8c8496298e2 to your computer and use it in GitHub Desktop.
Save dariocravero/2b3a9ec44997b1ed13a7b8c8496298e2 to your computer and use it in GitHub Desktop.
react-context
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>
)
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