skip to Main Content

I’m using i18next and redux-toolkit in my mobile project,

I got and menu-list static data, it simply like this.

const menuListData = [
 {
      id: 1,
      titleT: 'title1',          
  },
  {
      id: 2,
      titleT: 'title2',   
  },  ];
 export default menuListData;

just id and title, i got language store, lang files like this

export default en = { // also got for another lang
    translation: { 
      "title1": 'Title 1', 
      "title2": 'Title 2', 
    }
  }

I just want to use i18n translations in static file like this, but it gives error

import { useDispatch, useSelector } from "react-redux";
import React from "react";

const MenuList = (props) => {
    const i18n = useSelector((state) => state.langStore.i18n);
}
const titleTranslate = (metin) => {
    const i18n = useSelector((state) => state.langStore.i18n);
    return i18n.t(metin);
}
const menuListData = [
    {
        id: 1,
        titleT: i18n.t('title2'),
    },
    {
        id: 2,
        titleT: i18n.t('title2'),
    },
];
export default menuListData;

How can i make it, thank you

I made just and export file

const getMenuListData = (t) => [  
  {
    id: 1,
    titleT: t('title1'), 
  },
  {
    id: 2,
    titleT: t('title2'),  
  },    
];

export const data = getMenuListData; 

Then the component I call it , I gave it to i18n.t prop like tihs

 import { data } from "./menuListData";
 //in function
  const menuData = data(i18n.t);

Then it works, thanks all

2

Answers


  1. Chosen as BEST ANSWER
    const getMenuListData = (t) => [  
      {
        id: 1,
        titleT: t('title1'), 
      },
      {
        id: 2,
        titleT: t('title2'),  
      },    
    ];
    
    export const data = getMenuListData; 
    

    Then the component I call it , I gave it to i18n.t prop like tihs

     import { data } from "./menuListData";
     //in function
      const menuData = data(i18n.t);
    

  2. I just want to use i18n translations in static file like this, but it gives error

    You are getting errors because there’s no i18n.t function in the global scope of the file.

    You could convert the menuListData variable into a function e.g. getMenuListData and pass the translate function into it as an argument.

    const getMenuListData = (t) => [
        {
            id: 1,
            titleT: t('title2'),
        },
        {
            id: 2,
            titleT: t('title2'),
        },
    ];
    

    Then, just call it inside e.g. MenuList component:

    const MenuList = (props) => {
       const i18n = useSelector((state) => state.langStore.i18n);
       
       const data = getMenulistData(i18n.t);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search