Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variable / Constant in React Native

is there a way in React Native that I can define on a global variable all the strings that I will be using like in Android Development there is a String.xml where you can put all of your strings.

like image 318
Sydney Loteria Avatar asked Nov 03 '15 06:11

Sydney Loteria


People also ask

Can a global variable be constant?

Global variables aren't constant (you can change the value of a global variable, but you can only define a constant once). Constants aren't always global (you can declare a constant in a class). Also, global variables can be any type: scalar, array, or object. Constants can only be scalars.

How do you assign value to global variable in React Native?

Assume that you want to declare a variable called isFromManageUserAccount as a global variable you can use the following code. global. isFromManageUserAccount=false; After declaring like this you can use this variable anywhere in the application.

Can I use global variables in React?

You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this. context. varname .

What is constant in React Native?

React Native Navigation exposes a set of constants which can be used to get the dimensions of various navigation elements on the screen: StatusBar, TopBar and BottomTabs.


Video Answer


2 Answers

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 
like image 138
Chris Geirman Avatar answered Oct 01 '22 03:10

Chris Geirman


global in react native is like the window in web development.

// declare a global varible global.primaryColor = '***';  //now you can use this variable anywhere console.log(primaryColor); 
like image 30
Lin Jie Avatar answered Oct 01 '22 03:10

Lin Jie