A simple language localization with React hook
I wanted to create a simple language localization feature in a react project I was working on, and here’s how I did it;
Making it a hook
To make this feature reusable in other components I made it into a custom React hook.
👉🏽 Create a hook function called useTranslation()
in src/hooks/useTranslation.jsx
import React from 'react';
function useTranslation(locale: string) {
const [translations, setTranslations] = React.useState();
React.useEffect(() => {
(async function loadLangTranslations() {
setTranslations((await import(`../utils/lang/${locale}.json`)).default);
})();
}, [locale]);
const __trans = (key: string) => {
return translations[key] || key;
};
return [ __trans ];
}
export default useTranslation;
Defining the translation strings
To make things easy we create a JSON translation file and use the “default” translation of the string as the key. We can put the file into our utils
folder (I am sure you have that in your React project 😂).
👉🏽 Create the translation file called es.json
(translating our strings from English to Spanish) in utils/lang/es.json
. es
is the locale for Spanish language.
{
"I love coding Hello World.": "Me encanta programar Hello World."
}
Using the hook “useTranslation()
”
To retrieve a translated string from your language file es.json
use the function __trans
returned from the hook. You can do that by passing the default translation of your string to the function.
👉🏽 Retrieve the translated string with __trans(‘I love coding Hello World’)
.
import React from 'react';
import useTranslation from './hooks/useTranslation';
export default function App() {
const locale = "es";
const [ __trans ] = useTranslation(locale);
return (
<div>
<h3>Translate Hello World</h3>
<p>__trans('I love coding Hello World.')</p>
</div>
)
}
That’s it! By the way I was inspired by Laravel’s localization feature.
Thanks again for coming here! If you love anything React (JS) and Laravel (PHP), follow me on twitter so we learn 😍 together 💪🏽