Victor Ocnarescu
Posted on September 10, 2021
Do you need to support multiple languages in your React app? Thinking about which NPM package to install? What if I told you could develop your own multi language system in 5 minutes or less?
The dictionary
First you will need some file which will store the strings you want to translate and their correspondent translations. Think about this file as a key/value pair of translations.
For this I will use a JSON file:
// languages/es.json
{
"Hello world": "Hola mundo",
"Homepage": "Página principal",
// ... and so on
}
Adding translations to existing components
Let's assume you have this basic component that you wish to add the new translations.
// components/App.jsx
const App = () => {
return (
<div>
<h1>Hello world</h1>
<a href="#">Homepage</a>
</div>
);
};
Next you will want to add the new translations. One way to do it is to create a new function that translates the text.
// components/App.jsx
const App = () => {
return (
<div>
<h1>{translate('Hello world')}</h1>
<a href="#">{translate('Homepage')}</a>
</div>
);
};
But you can do better, so much better. Instead of the function, why not create a component? After all, components are the essence of React; they make React so wonderful.
// components/App.jsx
const App = () => {
return (
<div>
<h1><Translate>Hello world</Translate></h1>
<a href="#"><Translate>Homepage</Translate></a>
</div>
);
};
Much better, isn't it? Next step is to actually implement the Translate component.
Coding the Translate component
// components/Translate.jsx
import { useContext } from 'react';
import { AppContext } from '.';
import * as languages from '../languages';
const translate = (text) => {
const { language } = useContext(AppContext);
// return the translated text or the original text
if (Object.keys(languages).includes(language)) {
return languages[language][text] || text;
}
return text;
};
const Translate = ({ children }) => {
return translate(children);
};
export default Translate;
You will also need to keep the language
you want to translate in React context. Language should be kept as React context because it should be available anywhere in the app, similar to a "theme".
Closing thoughts
A simple multi language system in React can be developed fairly quick without using any third party packages. You will need:
- texts you want to translate stored in a JSON file
- store the
language
you want to translate your app in a React context - the
<Translate>
component that you can add anywhere in your app
This system does not handle edge cases (yet), but it's a great start. Bonus: your React components will be quite readable.
How do you implement multi language systems in your React apps? Let me know in the comment section below.
Posted on September 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 19, 2024