Created
September 19, 2019 10:58
-
-
Save kutyel/3dfcada9f9ab31a1f03ddf4020f681bb to your computer and use it in GitHub Desktop.
i18n with React Hooks, no external libraries!
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, { useReducer, createContext } from 'react' | |
import { propOr } from 'ramda' | |
import en from '../../assets/literals/EN' | |
import es from '../../assets/literals/ES' | |
const translations = { en, es } | |
const getTranslate = lang => key => propOr(key, key, translations[lang]) | |
const initialState = { lang: 'en', t: getTranslate('en') } | |
export const I18nContext = createContext(initialState) | |
export const I18nContextProvider = ({ children }) => { | |
const { Provider } = I18nContext | |
const reducer = (_, lang) => ({ lang, t: getTranslate(lang) }) | |
const [state, changeLang] = useReducer(reducer, initialState) | |
return <Provider value={{ ...state, changeLang }}>{children}</Provider> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment