Skip to content

Commit

Permalink
Refactor page title translation
Browse files Browse the repository at this point in the history
  • Loading branch information
RodBrowning committed Jul 27, 2022
1 parent 2373f83 commit 531ee80
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 16 deletions.
17 changes: 1 addition & 16 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,10 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<title></title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
<script>
const userLocale = () => {
return navigator && navigator.languages && navigator.languages.length
? navigator.languages[0]
: navigator.language;
};
const isPortuguese = () => {
return userLocale() === 'pt-BR';
};
if (isPortuguese()) {
document.title = 'Conversor de moedas';
} else {
document.title = 'Currency converter';
}
</script>
</body>
</html>
6 changes: 6 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import './App.scss';
import './App-mobile.scss';

import React, { useEffect, useRef, useState } from 'react';

Expand All @@ -7,6 +8,7 @@ import Flag from './Components/Flags';
import { ILatest } from './Types/Latest';
import { ISymbols } from './Types/Symbols';
import fetchFrom from './Utils/fetch';
import getTranslatedTitle from './Utils/translatedTitles';

export interface ICurrenciesInfo {
symbols: ISymbols;
Expand Down Expand Up @@ -46,6 +48,10 @@ const App: React.FC = () => {
}
};

useEffect(() => {
document.title = getTranslatedTitle();
}, []);

useEffect(() => {
if (!firstRender.current) return;
fetchCurrenciesAPI();
Expand Down
22 changes: 22 additions & 0 deletions src/Utils/translatedTitles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const TranslatedTitles: { [language: string]: string } = {
pt: 'Conversor de moedas',
es: 'Convertidor de moneda',
en: 'Currency converter',
};

const userLocale = () => {
const lang =
navigator && navigator.languages && navigator.languages.length ? navigator.languages[0] : navigator.language;
return lang.split('-')[0];
};

const hasTranslation = () => {
return TranslatedTitles[userLocale()] !== undefined;
};

const getTranslatedTitle = () => {
if (!hasTranslation()) return TranslatedTitles.en;
return TranslatedTitles[userLocale()];
};

export default getTranslatedTitle;

0 comments on commit 531ee80

Please sign in to comment.