Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global variables in React Native?

Tags:

react-native

In React Native I want to use global variables when I am moving between different screens

Can anyone help me how to achieve it?

like image 839
Dev Avatar asked Feb 23 '16 12:02

Dev


People also ask

How do you access global variables in React Native?

The way you should be doing it in React Native (as I understand it), is by saving your 'global' variable in your index. js, for example. From there you can then pass it down using props.

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 .

How do I set a global variable in react?

One way to declare a global variable in React is to attach a new variable as the property of the window object. For example, create a window.name variable in the index. js file like this: import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; window.name = "John"; const root = ReactDOM.


1 Answers

The global scope in React Native is variable global. Such as global.foo = foo, then you can use global.foo anywhere.

But do not abuse it! In my opinion, global scope may used to store the global config or something like that. Share variables between different views, as your description, you can choose many other solutions(use redux,flux or store them in a higher component), global scope is not a good choice.

A good practice to define global variable is to use a js file. For example global.js

global.foo = foo; global.bar = bar; 

Then, to make sure it is executed when project initialized. For example, import the file in index.js:

import './global.js' // other code 

Now, you can use the global variable anywhere, and don't need to import global.js in each file. Try not to modify them!

like image 89
Germinate Avatar answered Sep 19 '22 21:09

Germinate