Skip to content

Instantly share code, notes, and snippets.

@behnood-eghbali
Last active November 8, 2019 18:40
Show Gist options
  • Save behnood-eghbali/e8cd2e064a06cc4aa4abe7ed0313edae to your computer and use it in GitHub Desktop.
Save behnood-eghbali/e8cd2e064a06cc4aa4abe7ed0313edae to your computer and use it in GitHub Desktop.
Simple Example of React Context API
import React, { Component } from 'react'
import Toolbar from './Toolbar'
import {ThemeContext, themes} from './ThemeContext'
export default class App extends Component {
constructor(props) {
super(props)
this.state = {theme: themes.light}
this.toggleTheme = this.toggleTheme.bind(this)
}
toggleTheme() {
this.setState({theme: this.state.theme === themes.dark ? themes.light : themes.dark})
}
render() {
return (
<div className="App">
<ThemeContext.Provider value={this.state.theme}>
<Toolbar changeTheme={this.toggleTheme} />
</ThemeContext.Provider>
</div>
)
}
}
import React from 'react'
export const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
}
export const ThemeContext = React.createContext(themes.dark)
ThemeContext.displayName = 'ThemeColor'
import React, { Component } from 'react'
import {ThemeContext} from './ThemeContext'
export default class ThemedText extends Component {
static contextType = ThemeContext
render() {
const props = this.props
const theme = this.context
return (
<h2 {...props} style={{backgroundColor: theme.background, color: theme.foreground}}>Click Me!</h2>
)
}
}
import React from 'react'
import ThemedText from './ThemedText'
export default function Toolbar(props) {
return (
<div>
<ThemedText onClick={props.changeTheme} />
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment