Skip to content

Commit

Permalink
Merge pull request #10 from Quiddlee/add_multilang_functionality
Browse files Browse the repository at this point in the history
Add multilang functionality
  • Loading branch information
Quiddlee authored Dec 12, 2023
2 parents 358f87d + af29bd4 commit 757e639
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/locales/en.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const en = {
header: { h1: { h2: 'english' } },
button: 'Press me',
};

export default en;
6 changes: 6 additions & 0 deletions src/locales/ru.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const ru = {
header: { h1: { h2: 'русский' } },
button: 'Нажми',
};

export default ru;
7 changes: 6 additions & 1 deletion src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ import React from 'react';
import ReactDOM from 'react-dom/client';

import App from '@/App';

import LanguageProvider from './shared/Context/LanguageContext';

import '@/styles/index.css';

ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
<LanguageProvider>
<App />
</LanguageProvider>
</React.StrictMode>,
);
36 changes: 36 additions & 0 deletions src/shared/Context/LanguageContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { createContext, ReactNode, useCallback, useMemo, useState } from 'react';

import enTranslation from '@/locales/en';
import ruTranslation from '@/locales/ru';

type Translation = typeof enTranslation | typeof ruTranslation;

type LanguageContextType = {
language: string;
changeLanguage: () => void;
translation: Translation;
};

const TranslationFiles: { [key: string]: Translation } = {
en: enTranslation,
ru: ruTranslation,
};

export const LanguageContext = createContext<LanguageContextType>({} as LanguageContextType);

export default function LanguageProvider({ children }: { children: ReactNode }) {
const [language, setLanguage] = useState('en');

const changeLanguage = useCallback(() => {
const newLang = language === 'en' ? 'ru' : 'en';
setLanguage(newLang);
}, [language]);

const translation = TranslationFiles[language];
const contextValue = useMemo(
() => ({ language, changeLanguage, translation }),
[language, changeLanguage, translation],
);

return <LanguageContext.Provider value={contextValue}>{children}</LanguageContext.Provider>;
}
9 changes: 9 additions & 0 deletions src/shared/Context/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useContext } from 'react';

import { LanguageContext } from './LanguageContext';

const useLanguage = () => {
return useContext(LanguageContext);
};

export default useLanguage;

0 comments on commit 757e639

Please sign in to comment.