How to parse a value into a key from an outsource js file

Viewed 79

I have a question about parsing values from a different source into a key. Here is the environment:

Translation.js

export default {
    en: {
        translation: {
            Text: 'Text',
            Welcome:"Welcome text",
        }
    },
    tr: {
        translation: {
            Text: 'Selam',
            Welcome:"Hoşgeldiniz",
        }
    },
}

Now, I want to pars let say Welcome text into this which is a component of Ant.Design here:

https://ant.design/components/notification/

And in a different file like example.js, I have this and can react the translation.js

const openNotificationForNonActivated = type => {
  notification[type]({
    style:{marginTop: "42px"},
    message: 'Text',
    description: 'Welcome Text',
    duration: 5,
  });
};

I normally can get the translation value with this code:

{t("Welcome")}

I believe this is because I am trying to react it in a const value. So, how can I handle this? Any idea,

Best, thanks; Osman

1 Answers

If you are using react >= 16.8.0, you can create a custom hook that returns openNotificationForNonActivated and that so you can access the useTranlation hook, which will allow you to display the translated text

import React from 'react';
import { useTranslation } from 'react-i18next';
import { notification } from 'antd';

export const useNotification = () => {

  const { t } = useTranslation();

  const openNotificationForNonActivated = type => {
  notification[type]({
    style:{marginTop: "42px"},
    message: 'Text',
    description: t('welcome'),
    duration: 5,
  });
 };

  return { openNotificationForNonActivated };
};

and you can call your function in your component as follow

const {openNotificationForNonActivated } = useNotification();

openNotificationForNonActivated('type');
Related