16

I haven't been able to find anything like

$rootScope

for React Native and I want to share a couple variables between different Views.

kennysong
  • 504
  • 2
  • 6
  • 23

4 Answers4

8

For example, you can export class with static properties and then import there when need.

In main.js for example:

export class AppColors {
    static colors = {main_color: "#FFEB3B", secondary_color: "#FFC107"}
}

In other file, where need to get this colors

import { AppColors } from './main.js';

class AnotherPage {
    constructor() {
        super();
        console.log(AppColors.colors); // youla! You will see your main and secondary colors :)
    }
}
Yegor
  • 1,088
  • 1
  • 10
  • 14
7

Storing variables in the global scope is a bit of an anti-pattern in React. React is intended to be used with a one-way data flow, meaning data flows down from components to their children. This is achieved through the passing of props.

In order to share a value between multiple views, you would either need to store the data on a shared parent component and pass it down as a prop OR store it in a separate entity that is responsible for data management. In ReactJS this is achieved through patterns like Flux, but I'm not sure about the options for react-native.

Jakemmarsh
  • 4,601
  • 12
  • 43
  • 70
  • 12
    Agree that this is generally an antipattern, but that doesn't mean that you should never use globals in any circumstance. React Native itself defines a global variable in Javascript called `__DEV__`. How is this done, and how can I create something similar, e.g. `__MYDEV__`? (It looks like this may not be possible, and that the closest you can get is an [environment variable](http://stackoverflow.com/questions/33117227/setting-environment-variable-in-react-native).) – Lane Rettig Feb 01 '16 at 22:32
4

Step 1. create ConstantFile.js File and put this code.

export class ConstantClass {
    static webserviceName = 'http://172.104.180.157/epadwstest/';
    static Email = 'emailid';
    static Passoword = 'password';
}

Step 2. Access as like below. But before that, you need to import your js file to particular class file something like that

import { ConstantClass } from './MyJS/ConstantFile.js';

ConstantClass.webserviceName

ConstantClass.Email

ConstantClass.Passoword
kalpesh
  • 1,285
  • 1
  • 17
  • 30
0

You can store those values in parent components state. Then pass methods changing those values via props or context / or like @Jakemmarsh suggested - use Flux/Redux approach.

OR, you can use AsyncStorage. Its useful for storing app data like tokens and such.

j2ko
  • 2,479
  • 1
  • 16
  • 29
adamTrz
  • 143
  • 1
  • 2
  • 8