I use i18n package in my React application to translate some texts. But I can't iterate through an array of objects which is my translation data.
I want to do iterating through socials
array and show it in my template. but when I do that, it says: socials.map is not a function
this is my translation json file:
{
"socials": [
{
"name": "Github",
"url": "#"
},
{
"name": "Twitter",
"url": "#"
},
{
"name": "Linkedin",
"url": "#"
},
{
"name": "Instagram",
"url": "#"
}
]
}
this is my jsx code:
import { useTranslation } from 'react-i18next';
const Content = () => {
const { t, i18n } = useTranslation();
const socials = t('socials', { returnObjects: true });
rerurn (
<div className="flex">
{socials.map((social) => (
<a href={social.url}>{social.name}</a>
))}
</div>
);
}
export default Content;
How can I solve this problem?
Your translations are probably lazy loaded, and you're probably also not using Suspense. This means the translations are not ready for the first render, and you need to check the ready flag: https://react.i18next.com/latest/usetranslation-hook#not-using-suspense
import { useTranslation } from "react-i18next";
const Content = () => {
const { t, i18n, ready } = useTranslation();
if (!ready) return "loading translations...";
const socials = t("socials", { returnObjects: true });
return (
<div className="flex">
{socials.map((social) => (
<a href={social.url}>{social.name}</a>
))}
</div>
);
};
export default Content;