1

I have a function that I am using for string externalization to translate and localize the content of a site.

const t = (string_to_trans) => {
    return lang[string_to_trans];
}

I would like to make the function t globally accessible in all components. I've found that I can do it by attaching it to global or window like

global.t = t

without my App.js file, however to call that, I seem to have to use

global.t('string_to_trans');

Is there a way of not having to use global or window to do this so I can call it using only

t('string_to_trans');
Joe
  • 655
  • 1
  • 11
  • 24
  • Please clarify: is your question about how to make things available to global scope in React or how to not use the `global` to call your function? – jmargolisvt Feb 23 '19 at 18:44
  • 1
    Possible duplicate of [Define global variable with webpack](https://stackoverflow.com/questions/37656592/define-global-variable-with-webpack) – JJJ Feb 23 '19 at 18:44
  • You could put the `t` function in a separate module e.g. `utils.js` and import it in every file you need it. – Tholle Feb 23 '19 at 18:45
  • So in VueJs I was able to attach a similar function globally and not import the function everywhere. I don't want to have to import it using the utils.js pattern as it would have to be imported so many places. Is there some way of attaching it to the App so that it can be called everywhere without importing or a longer name like global.t as an example. – Joe Feb 23 '19 at 18:59
  • *as it would have to be imported so many places* - so you would have to import React and other packages that are used all over the app. This is the right thing to do. If you have problems importing them, use IDE that can do autoimports for you. – Estus Flask Feb 23 '19 at 19:45

1 Answers1

0

The React way to do this would be to use Context. https://reactjs.org/docs/context.html

<Context.Provider
    value={{
        translate: (string_to_trans) => lang[string_to_trans]
    }}
>
    {this.props.children}
</Context.Provider>

You could even do

<Context.Provider value={lang}>{this.props.children}</Context.Provider>

then directly access your translations dictionary inside the components.

Radu Luncasu
  • 975
  • 10
  • 17