i18next Guide (WIP)

Interpolation Example


Locale: 

My name is Michael and I was born in London.

Code

1import PropTypes from 'prop-types';
2import { useState } from 'react';
3import { withTranslation } from '../../i18n';
4
5const InterpolationExample = ({ t }) => {
6  const [fields, setField] = useState({ name: 'Michael', location: 'London' });
7  return (
8    <div>
9      <dl>
10        <dt>
11          <label htmlFor="name">{t('interpolation:userName')}: </label>
12        </dt>
13        <dd>
14          <input
15            id="name"
16            onChange={(e) => setField({ ...fields, name: e.target.value })}
17            defaultValue={fields.name}
18          />
19        </dd>
20        <dt>
21          <label htmlFor="location">{t('interpolation:userLocation')}: </label>
22        </dt>
23        <dd>
24          <input
25            id="location"
26            onChange={(e) => setField({ ...fields, location: e.target.value })}
27            defaultValue={fields.location}
28          />
29        </dd>
30      </dl>
31      <p>{t('interpolation:aboutPerson', fields)}</p>
32    </div>
33  );
34};
35
36InterpolationExample.propTypes = {
37  t: PropTypes.func.isRequired,
38};
39
40export default withTranslation('interpolation')(InterpolationExample);
41

interpolation/en.json

{
  "userName": "Name",
  "userLocation": "Location",
  "aboutPerson": "My name is {{name}} and I was born in {{location}}."
}

interpolation/de.json

{
  "userName": "Name",
  "userLocation": "Wohnort",
  "aboutPerson": "Mein Name ist {{name}} und ich wurde in {{location}} geboren."
}

interpolation/ru.json

{
  "userName": "Имя",
  "userLocation": "Город",
  "aboutPerson": "Меня зовут {{name}} и я родился в {{location}}."
}

Why?

  • In the case of dynamic text, it's not enough to simply translate and swap word for word, because different languages will order their words differently. For example, switch to German and watch the verb take the end of the sentence instead of the city name.