Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React Native have global scope? If not, how can I mimic it? [duplicate]

I haven't been able to find anything like

$rootScope

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

like image 225
kennysong Avatar asked Aug 24 '15 21:08

kennysong


People also ask

Why is React Native so difficult?

React Native has a gesture responder system. It will run the entire lifecycle of all the gestures in the mobile applications. But when it comes to complex ones, the developers will still face some difficulties. This is because iOS and Android apps have a unified API which are quite different from each other.


3 Answers

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 :)
    }
}
like image 61
Yegor Avatar answered Oct 19 '22 03:10

Yegor


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.

like image 28
Jakemmarsh Avatar answered Oct 19 '22 03:10

Jakemmarsh


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
like image 4
kalpesh Avatar answered Oct 19 '22 04:10

kalpesh