skip to Main Content

Please how do I call action[EDIT].title using t() function in order to return the string "Edit". The EN.js file that contains my translation is like this

// EN.js

const EDIT = "EDIT";
const DELETE = "DELETE";

action: {
    [EDIT]: {
      title: 'Edit',
    },
    [DELETE]: {
      title: 'Delete',
    },
}

and my config is

// i18n.js

const resources = {
  en: {
    translation: EN
  },
  de: {
    translation: DE
  },
};
i18next
  .use(initReactI18next)
  .init({
    resources,
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false,
    },
    debug: true,
  });

export default i18next;

I expect for t(action[EDIT].title) to return the string ‘Edit’

2

Answers


  1. To access the nested keys in your translation file with dynamic values, you should modify your translation object to include a namespace or key path. Then, you can use the t() function with the path.

    First, update your EN.js file to include a namespace or key path for the action objects:

    // EN.js
    const EDIT = "EDIT";
    const DELETE = "DELETE";
    
    const EN = {
      action: {
        [EDIT]: {
          title: 'Edit',
        },
        [DELETE]: {
          title: 'Delete',
        },
      },
    };
    
    export default EN;
    

    Now, you can access the nested key using the t() function like this:

     const editTitle = t('action.EDIT.title');
    
    Login or Signup to reply.
  2. I encountered this kind of blocker and using a dot notation instead of bracket notation worked for me. I didn’t need to modify the translation file tho but simply doing t('action.EDIT.title') worked.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search