Skip to content

Instantly share code, notes, and snippets.

@kutyel
Created September 19, 2019 10:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kutyel/3dfcada9f9ab31a1f03ddf4020f681bb to your computer and use it in GitHub Desktop.
Save kutyel/3dfcada9f9ab31a1f03ddf4020f681bb to your computer and use it in GitHub Desktop.
i18n with React Hooks, no external libraries!
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