Skip to content

Instantly share code, notes, and snippets.

@rafaelcamargo
Last active December 7, 2023 06:42
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 rafaelcamargo/2b35ab21f8e5829247d25e94e3faa308 to your computer and use it in GitHub Desktop.
Save rafaelcamargo/2b35ab21f8e5829247d25e94e3faa308 to your computer and use it in GitHub Desktop.
HTML within React i18next translations
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React i18next</title>
<script src="https://cdn.jsdelivr.net/npm/@babel/standalone@7.13.8/babel.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/i18next@23.7.6/dist/umd/i18next.min.js"></script>
<script src="https://unpkg.com/react-i18next@13.5.0/react-i18next.min.js"></script>
<style>
html,
body {
text-align: center;
}
h1 {
margin: 150px 0 0;
font-weight: normal;
}
p {
margin: 10px 0 0;
}
select {
margin-top: 50px;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
(function () {
const { createRoot } = ReactDOM;
const { useTranslation, initReactI18next, Trans } = ReactI18next;
i18next.use(initReactI18next).init({
resources: {
en: {
translation: {
greeting: "Hi, my name is <b>Rafael</b> and I'm a programmer.",
tagline: 'Visit my <a>Portfolio</a> to learn more.'
}
},
pt: {
translation: {
greeting: 'Olá, sou programador e me chamo <b>Rafael</b>.',
tagline: 'Visite meu <a>Portfolio</a> para saber mais.'
}
}
},
lng: 'en',
fallbackLng: 'en',
interpolation: {
escapeValue: false
}
});
const App = () => {
const { t, i18n } = useTranslation();
const languages = [
{ value: 'en', label: 'English' },
{ value: 'pt', label: 'Português' }
];
return (
<>
<h1>
{<Trans
i18nKey="greeting"
components={{ b: <strong /> }}
/>}
</h1>
<p>
{<Trans
i18nKey="tagline"
components={{ a: <a href="https://rafaelcamargo.com/" /> }}
/>}
</p>
<select
aria-label="language"
value={i18next.language}
onChange={evt => i18n.changeLanguage(evt.target.value)}
>
{languages.map(({ label, value }) => (
<option value={value}>{label}</option>
))}
</select>
</>
);
}
const root = createRoot(document.getElementById('root'));
root.render(<App />);
}())
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment