rmdort / react-redux-multilingual

A simple and slim multi-lingual component for React with Redux without react-intl or react-i18n
41 stars 14 forks source link

Access translate function in a file where we don't have a react-component #14

Closed Vishal1419 closed 6 years ago

Vishal1419 commented 6 years ago

I have a file which has only some helper functions. I want to use translate in that file. I don't want to pass translate as a parameter to the function as I have to make changes to many files. Is there any way that I can have access to translate function in any file which does not use react?

By the way I don't have any problem to use react in such files. I mean I can import React if translate needs it.

rmdort commented 6 years ago

You can now pass a custom translate prop to IntlProvider . Released on 2.0.2

https://github.com/rmdort/react-redux-multilingual/blob/master/src/provider.js#L29

Vishal1419 commented 6 years ago

Sorry, i am late to this issue again. But what I want to say is I don't have a react-component in the file but I have a function, so I don't have props available. And I don't want to pass translate as a parameter to that function. How can I access translate function there? Is there any way to import translate function directly without using withTranslate?

rmdort commented 6 years ago

This is meant to be used as a react provider. If you want a custom translate function

function yourtranslate () {}

<IntlProvider translate={yourtranslate} />
sagarpanchal commented 5 years ago

translate.js

import { translateKey, supplant } from "react-redux-multilingual/src/utils";
import { store } from "../../store"; // Redux Store
import i18n from "../../i18n"; // translations

/**
 * Access translate function in a file where we don't have a react-component
 * (https://github.com/rmdort/react-redux-multilingual/issues/14)
 *
 * @param {String} k key
 * @param {Object} p placeholder
 */
export default (k, p) => {
  const { locale: l } = store.getState().Intl;
  const r = (this || translateKey)(k, i18n[l]["messages"]);
  return typeof p === "undefined" ? r : supplant(r, p);
};