Last active
November 8, 2019 18:40
-
-
Save behnood-eghbali/e8cd2e064a06cc4aa4abe7ed0313edae to your computer and use it in GitHub Desktop.
Simple Example of React Context API
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, { 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> | |
) | |
} | |
} |
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' | |
export const themes = { | |
light: { | |
foreground: '#000000', | |
background: '#eeeeee', | |
}, | |
dark: { | |
foreground: '#ffffff', | |
background: '#222222', | |
}, | |
} | |
export const ThemeContext = React.createContext(themes.dark) | |
ThemeContext.displayName = 'ThemeColor' |
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, { 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> | |
) | |
} | |
} |
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' | |
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