Created
January 29, 2020 12:13
-
-
Save dmitrydyomin/24aa01c045b09a633683b76ca5bf6c7a to your computer and use it in GitHub Desktop.
Simple i18n provider and hook for React
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, { createContext, useContext, useState } from 'react'; | |
import PropTypes from 'prop-types'; | |
import en from './en'; | |
const TranslationContext = createContext(); | |
export const useTranslation = () => useContext(TranslationContext); | |
const data = { | |
en, | |
}; | |
const untranslated = {}; | |
const TranslationProvider = ({ children }) => { | |
const [state, setState] = useState({ | |
locale: 'en', | |
setLocale: locale => setState(v => ({ ...v, locale })), | |
t: (s) => { | |
if (data.en[s]) { | |
return data.en[s]; | |
} | |
if (typeof untranslated[s] === 'undefined') { | |
untranslated[s] = s; | |
} | |
return `*${s}*`; | |
}, | |
}); | |
return ( | |
<TranslationContext.Provider value={state}> | |
{children} | |
<pre>{JSON.stringify(untranslated, null, 2)}</pre> | |
</TranslationContext.Provider> | |
); | |
}; | |
TranslationProvider.propTypes = { | |
children: PropTypes.node, | |
}; | |
TranslationProvider.defaultProps = { | |
children: null, | |
}; | |
export default TranslationProvider; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment