DEV Community

Kay Gosho
Kay Gosho

Posted on

3 1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay