DEV Community

Kay Gosho
Kay Gosho

Posted on

Global helper in React, React Native

It is common situation that we would like to define some global functions in any projects.

Without global function, we should write import statement every time.

But is this against react philosophy? Don't worry, I found the following code in the real world project.

// make the i18n function "t" global so we don't have to import it in basically every file
import { t, jt } from "c-3po";
global.t = t;
global.jt = jt;
Enter fullscreen mode Exit fullscreen mode

https://github.com/metabase/metabase/blob/ed83df6d939b94b8193601e74676ec32b46a989a/frontend/src/metabase/app.js#L10

I defined a global function _ (lodash) in current React Native project and I don't have any problems.

How to

Very easy.

Write this in your bootstrap file (e.g. app.js)

import _ from 'lodash'

global._ = _
Enter fullscreen mode Exit fullscreen mode

Then you can use _ everywhere without import explicitly.

<Text style={styles.title}>
  {_.truncate(someText, { length: 22 })}
</Text>
Enter fullscreen mode Exit fullscreen mode

Tell ESLint

ESLint will regard global function as error. So let's add the following config to .eslintrc:

{
  //...
  "globals": {
    "_": false
  },
  //...
}
Enter fullscreen mode Exit fullscreen mode

Note that a lot of global functions might cause readability, dependency and testability problems.

Top comments (0)