Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LanguageProvider
import React, {useState, useEffect, useContext} from 'react';
import en from '../lang/en.json';
import zh from '../lang/zh.json';
import * as RNLocalize from 'react-native-localize';
import App from '../App';
type LanguageContextType = {
hello: string;
};
const LanguageContext = React.createContext<LanguageContextType>(
{} as LanguageContextType,
);
const languageObj = {
en: en,
'zh-Hans-US': zh,
};
export const LanguageContextProvider: React.FC = ({children}) => {
const [selectedLanguage, setSelectedLanguage] = useState('en');
useEffect(() => {
const currentLanguage = RNLocalize.findBestAvailableLanguage(
Object.keys(languageObj),
);
setSelectedLanguage(currentLanguage?.languageTag || 'en');
}, []);
const value = {
...languageObj[selectedLanguage as 'en' | 'zh-Hans-US'],
};
return (
<LanguageContext.Provider value={value}>
<App />
</LanguageContext.Provider>
);
};
export const useTranslation = () => useContext(LanguageContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment