6

Just started using i18next and having a bit of issues translating the following data.

export const educationData = [
  { education: "Some education 1", timeframe: "2017 - 2018", id: 1 },
  { education: "Some education 2", timeframe: "2016 - 2017", id: 2 },
  { education: "Some education 3", timeframe: "2015 - 2016", id: 3 },
  { education: "Some education 4", timeframe: "2014 - 2015", id: 4 }
];

JSON in locales for different languages looks like:

"education": {
  "heading": "Education",
  "educationData": [
    {
      "id": 1,
      "education": "Some education 1",
      "timeframe": "2017 - 2018"
    },
    {
      "id": 2,
      "education": "Some education 2",
      "timeframe": "2016 - 2017"
    },
    {
      "id": 3,
      "education": "Some education 3",
      "timeframe": "2015 - 2016"
    },
    {
      "id": 4,
      "education": "Some education 4",
      "timeframe": "2014 - 2015"
    }
  ]
}

Component looks like:

import React from "react";
import { useTranslation } from "react-i18next";
import { educationData } from "../data/educationData";
import Education from "./Education.js";

function ListEducation() {
  const { t } = useTranslation();
  return (
    <div className="education py-1">
      <h2>{t("education.heading")}</h2>
      <hr />
      {educationData.map((edu) => (
        <Education
          key={edu.id}
          education={edu.education}
          timeframe={edu.timeframe}
        />
      ))}
    </div>
  );
}

export default ListEducation;

How do i get the translations to work in the .map() function? Outside of .map() something like t("education.educationData.0.education") works fine.

Inside .map function it just outputs "education.educationData.0.education" as a string.

5
  • Where are you using the t("education.educationData.0.education")? Commented May 14, 2020 at 19:00
  • This is just to show that outside of the map function it shows the object data which works fine but inside the map function it show a string instead. Commented May 15, 2020 at 7:22
  • Can you share the your tried code? Commented May 15, 2020 at 9:10
  • codesandbox.io/s/dreamy-wozniak-6cdnb The locales are in the public folder. Commented May 16, 2020 at 10:23
  • Anyone know how to get this working? Commented Jun 3, 2020 at 21:01

2 Answers 2

12

You can get access to an array from file with translations using:

t('education.educationData', { returnObjects: true })

and then easily map through this array.
Source: i18next documentation: Arrays

Sign up to request clarification or add additional context in comments.

Comments

4

You can try this

{t(`education.educationData.${id}.${education}`)}

You're basically concatenating the string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.