I followed the article here: https://dev.to/adrai/how-to-properly-internationalize-a-react-application-using-i18next-3hdb.
Now I want to know if there is a way to pass an argument into the string pulled from the .json file.
public/locales/en/translation.json
{
"GREETING": "Hello ${name}, nice to see you."
}
src/i18n.ts
import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';
i18n
// i18next-http-backend
// loads translations from your server
// https://github.com/i18next/i18next-http-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: false,
fallbackLng: 'en',
interpolation: {
escapeValue: false // not needed for react as it escapes by default
}
});
export default i18n;
src/App
import React, {useState} from 'react';
import {useTranslation} from 'react-i18next';
function App() {
const {t} = useTranslation();
const [name] = useState('John Doe');
return (
<div>
<p>{t('GREETING')}</p>
</div>
);
}
export default App;
currently: the browser is showing "Hello ${name}, nice to see you."
What I need: the browser to show "Hello John Doe, nice to see you."
CodePudding user response:
By default i18next uses different format prefixes ({{
) and suffixes (}}
)
Try writing your translations like this:
{
"GREETING": "Hello {{name}}, nice to see you."
}
And the interpolation variable like this:
<p>{t('GREETING', {name: "John Doe")}</p>
CodePudding user response:
You would have to pass the variable as the second argument to the "t" function.
<p>{t('GREETING', {name: "John Doe")}</p>