0

In react native, need to set ~10 variables relating to screen sizes BEFORE the user sees all the screens in the app. I can do this in the AppLoadingScreen.js (as that is universal in terms of size). I have the following function and switch statement (but i don't know how exactly to run it). Once they're set, i want to ensure all the screens (or .js files) have these variables set and ready to go.

import {StyleSheet, Dimensions } from 'react-native'

export function whichScreen() {
  const dim = Dimensions.get('window');

  if ((dim.width === 375 )){
    return 0;
  }
  else if((dim.width === 414)){
    return 1;
  }
  else if((dim.width === 484 )){
    return 2;
  }
  else if((dim.width === 578 )){
    return 3;
  }
}


getScreenParams=()=>{

  let size = this.whichScreen();

  switch(size) {

      case 0:
        this.setState({ marginforcontainer: 2, marginforSignIn: 5, ....}) //Don't even know which class to put the state variables in?
        break;

      case 1:
        this.setState({ marginforcontainer: 6, marginforSignIn: 7, ....}) //Don't even know which class to put the state variables in?
        break;

      case 2:
        this.setState({ marginforcontainer: 8, marginforSignIn: 6, ....}) //Don't even know which class to put the state variables in?
        break;

      case 3:
        this.setState({ marginforcontainer: 4, marginforSignIn: 1, ....}) //Don't even know which class to put the state variables in?
        break;

      default:

    }
  }

I dont want to have to run the getScreenParams() function EVERY TIME a user moves onto each of the screens, thats just awful. Also putting them in AsyncStorage and calling a getItem() from AsyncStorage each time is expensive.

How do i run this once while the app is loading and set the variables i need??

chai86
  • 425
  • 2
  • 14
  • 34
  • 1
    If you are not using a global store (like redux) you can use the context API to share values across the app - https://reactjs.org/docs/context.html – topched Mar 13 '20 at 00:39
  • @topched Context wont work here because not every child is related to the parent, i need the variables accessible within my whole app! – chai86 Mar 13 '20 at 10:03

0 Answers0