Global Variable / Constant in React Native

What’ I’ve done is create a globals module…

// File: Globals.js

module.exports = {
  STORE_KEY: 'a56z0fzrNpl^2',
  BASE_URL: 'http://someurl.com',
  COLOR: {
    ORANGE: '#C50',
    DARKBLUE: '#0F3274',
    LIGHTBLUE: '#6EA8DA',
    DARKGRAY: '#999',
  },
};

Then I just require it at the top…

const GLOBAL = require('../Globals');

And access them like so…

GLOBAL.COLOR.ORANGE

_____________________

UPDATE on Feb 10, 2018

This seems to be a pretty popular and useful answer, so I thought I should update it with the more current syntax. The above still works in CommonJS module systems, but now days you’re just as likely to run into ES6 and importmodules rather than require them.

ECMAScript Modules (ESM) Syntax

// File: Globals.js

export default {
  STORE_KEY: 'a56z0fzrNpl^2',
  BASE_URL: 'http://someurl.com',
  COLOR: {
    ORANGE: '#C50',
    DARKBLUE: '#0F3274',
    LIGHTBLUE: '#6EA8DA',
    DARKGRAY: '#999',
  },
};

// to use…

import GLOBALS from '../Globals'; // the variable name is arbitrary since it's exported as default

// and access them the same way as before

GLOBALS.COLOR.ORANGE

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)