Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native StackNavigator initialRouteName

In React Native Navigation library 'react-navigation'

How could I set StackNavigator initialRouteName by AsyncStorage?

function getInitialScreen() {
    AsyncStorage.getItem('initialScreen')
        .then(screenName => {
            return (screenName)
                ? screenName
                : 'Login';
        })
        .catch(err => {});
}

const Navigator = StackNavigator({
    Splash: { screen: Splash },
    Login: { screen: Login },
    WebPage: { screen: WebPage }
}, {
    initialRouteName: getInitialScreen()
});
like image 307
amorenew Avatar asked Oct 11 '17 08:10

amorenew


People also ask

What is initialRouteName in react native?

initialRouteName - Sets the default screen of the stack. Must match one of the keys in route configs.

How do you set initialRouteName dynamically in the react native?

another way to handle this is to use a switchnavigator and have a screen that you show when you are fetching the async data, then navigate to the appropriate initial route with params when necessary. see docs for a full example of this.

What is stack screen in react native?

Stack Navigator provides a way for your app to transition between screens where each new screen is placed on top of a stack. By default the stack navigator is configured to have the familiar iOS and Android look & feel: new screens slide in from the right on iOS, use OS default animation on Android.


1 Answers

Changing InitialRouteName with multiple Route depending upon your requirement. I have got it working this way.

create router file import all your screens.

export a stateless function call it createRootNavigator with params as (load="<Your initial screen>")

export const createRootNavigator = (load="<Your Initial Screen>") => {
  return stackNavigator({
     Initialize: {
       screen: Initialize,
     },
     Main: {
      screen: Main,
     },
     { 
       initialRouteName: load
     }
  })
}

In your main app,

state = {
  load: "<Your Initial Screen>"
}

eg:

state = {
   load: "Initialize" // value is string
}

Set the state accordingly in componentDidMount() method. And finally render new layout.

render() {
  const Layout = createRootNavigator(this.state.load);
  <Layout />
}

The above method worked fine for me. Hope it helps somebody.

like image 53
Srinivas Avatar answered Oct 04 '22 04:10

Srinivas