Created
May 23, 2019 13:41
-
-
Save jaksm/c4c6b2e8f677fc74a6e7485ee5354676 to your computer and use it in GitHub Desktop.
Multi language React Context Api
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, {Component} from 'react'; | |
import './App.css'; | |
import IntlContext from "./intl.context"; | |
import Bla from "./Bla" | |
import en from "./locales/en" | |
import sr from "./locales/sr" | |
import LanguageSwitch from "./LanguageSwitch"; | |
const translations = { en, sr }; // prevodi | |
class App extends Component { | |
state = { | |
locale: "en" // default | |
}; | |
render() { | |
const locale = localStorage.getItem("locale") || this.state.locale; | |
return ( | |
<IntlContext.Provider value={translations[locale]}> | |
<Bla /> | |
{/* LanguageSwitch mora da stoji u App.js, dok ne nadjemo bolje resenje */} | |
<LanguageSwitch | |
onSwitch={(locale) => this.setState({ locale })} | |
locale={locale} | |
/> | |
</IntlContext.Provider> | |
); | |
} | |
} | |
export default App; |
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, { Component } from "react" | |
import IntlContext from "./intl.context" | |
class Foo extends Component { | |
static contextType = IntlContext; | |
render() { | |
return ( | |
<div> | |
{this.context.greet} | |
</div> | |
); | |
} | |
} | |
export default Foo |
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 { createContext } from "react" | |
export default createContext() |
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, {Component} from "react" | |
class LanguageSwitch extends Component { | |
handleLanguageSwitch = () => { | |
const locale = this.props.locale === "en" ? "sr" : "en"; | |
this.props.onSwitch(locale); | |
localStorage.setItem("locale", locale); | |
}; | |
render() { | |
return ( | |
<strong | |
onClick={this.handleLanguageSwitch} | |
> | |
{this.props.locale.toUpperCase()} | |
{/* Obrnut redosled */} | |
{/*{this.props.locale === "en" ? "SR" : "EN"}*/} | |
</strong> | |
); | |
} | |
} | |
export default LanguageSwitch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment