Initial route after user logged in?
In Navigator, i change initial route passing a function to the prop definition, ex:
<Navigator initialRoute={ this.initialRoute() } />
How can i do the same in react-navigation?
Edit
With the navigator, i connect the state and the navigator with connect(state)(navigator), but if i do the same with react-navigation, it obviously doesn't works because that is not the correct way to do that. Other way to do that is using the store.getState() in a function in initialRouteName, but it look's weird for me, i want to use react-redux, but i don't know how. Is there a way to do this?
const routeConfig = {...};
const stackRouterConfig = { initialRouteName: initialRoute() };
const Navigator = StackNavigator(routeConfig, stackRouterConfig);
Does this help?
Thanks @thotegowda,
I've done this, but i do not understand how i do that using redux (with react-redux), i forgot to say this in the question, srry.
With the navigator, i connect the state and the navigator with connect(state)(navigator), but if i do the same with react-navigation, it obviously doesn't works because that is not the correct way to do that.
Other way to do that is using the store.getState() in a function in initialRouteName, but it look's weird for me, i want to use react-redux, but i don't know how.
Is there a way to do this?
that worked for me :
const RootNavLogged = StackNavigator({
...
},{
initialRouteName : 'Home'
});
const RootNav = StackNavigator({
...
},{
initialRouteName : 'Login'
});
class App extends Component {
render(){
if (this.props.userLogged == true ){
return (
<RootNavLogged/>
)
} else {
return(
<RootNav/>
)
}
}
}
..
export default connect(mapStateToProps)(App)
@AlpZero : Is it possible to programatically set the initialRouteName on tab navigator. My home screen is a springboard (StackNavigator) and pressing an icon opens the tab navigator.
Would you know how I could navigate from Home to Share in the following example?
export const Tabs = TabNavigator({
Calendar: {
screen: Calendar,
},
Share: {
screen: Share,
},
});
export const Stack = StackNavigator({
Home: {
screen: Home
},
Tabs: {
screen: Tabs,
}
})
@AlpZero doesn't it remove the animation? I mean, I want to animate when going from the login to home, but don't want to show any option to goback. Like a push followed by a replace...
@vishim do you find any solution?
@arminghm I have a hack at the moment. I have created a routerConfig object and then have various entry points:
const TabEntryCalendar = TabNavigator(routeConfig, {
initialRouteName: 'Calendar',
...tabConfig,
});
const TabEntryShare = TabNavigator(routeConfig, {
initialRouteName: 'Share',
...tabConfig,
});
....
and then the top level stack navigator instantiates
const TabsInsideStack = StackNavigator({
Home: {
screen: Home
},
TabEntryCalendar: {
screen: TabEntryCalendar,
},
TabEntryShare: {
screen: TabEntryShare,
},
....
....
Hope it helps. If someone could suggest a better way, that would be greatly appreciated!
@vishim , @arminghm @AlpZero Guys, after taking some time to dig into the source, I found out a trick for that. Technically we want to avoid the user to go back to the previous screen, that's all. What I did is to add on the route configuration the following:
const AppRouteConfigs = {
TheRoute: {
...
navigationOptions: {
cardStack: {
gesturesEnabled: false
}
}
}
This will avoid the user to swipe back to the previous screen. After that, on my reducer, I did this:
const routeName = state.routes[state.index].routeName
if (Routes[routeName] &&
Routes[routeName].navigationOptions &&
Routes[routeName].navigationOptions.cardStack &&
Routes[routeName].navigationOptions.cardStack.gesturesEnabled === false) {
return state
}
This way the user can't go back back on this screens.
@vishim Actually I did the same thing as you did. But I think It could be better if we can navigate to each tab using their keys with the navigate function.
@SidFerreira What if you use resetAction?
@arminghm it will not have the animation, and I want the animation
So basically redirecting user to the Home screen in nested navigator scenario, I did this little trick. As react-navigation does not provide a way to set the initialRouteName, we dispatch an action to navigate to the drawer stack i.e. Home screen.
Here is our Navigation file with Redux integration, which will show you the nesting of various navigators
// drawer stack
const DrawerStack = StackNavigator({
DashboardScreen: { screen: DashboardScreen, navigationOptions: { title: 'Event', drawerLabel: 'Event' } },
MyAccountScreen: { screen: MyAccountScreen, navigationOptions: { title: 'My Account', drawerLabel: 'My Account' } },
}, {
headerMode: 'screen',
navigationOptions: ({ navigation }) => ({
headerStyle: {
backgroundColor: Colors.darkBlue,
shadowOpacity: 0,
shadowOffset: { height: 0, },
elevation: 0,
},
headerTitleStyle: {
color: Colors.snow,
alignSelf: 'center',
},
headerLeft: navigation.state.routeName == 'DashboardScreen' ? <TouchableOpacity activeOpacity={0.2} style={styles.leftIcon} onPress={() => {
navigation.dispatch(NavigationActions.navigate({ routeName: 'DrawerOpen' }));
}}><Image large source={Images.Bar} style={styles.bar} /></TouchableOpacity> : <TouchableOpacity activeOpacity={0.2} style={styles.leftIcon}
onPress={() => {
if (navigation.state.params && navigation.state.params.onBackPress) {
navigation.state.params.onBackPress();
}
navigation.goBack();
}}><Icon name="angle-left" size={28} color="snow" /></TouchableOpacity>,
headerRight: <TouchableOpacity activeOpacity={0.2} style={styles.leftIcon} onPress={() => {
navigation.dispatch(NavigationActions.navigate({ routeName: 'DrawerOpen' }));
}}><Icon size={28} color="snow" /></TouchableOpacity>
})
})
const DrawerNavigation = DrawerNavigator({
DrawerStack: { screen: DrawerStack }
}, {
contentComponent: DrawerComponent,
drawerWidth: 300,
})
// login stack
const LoginStack = StackNavigator({
LoginScreen: { screen: LoginScreen },
RegisterScreen: { screen: RegisterScreen },
ForgotPasswordScreen: { screen: ForgotPasswordScreen },
CountryListScreen: { screen: CountryListScreen },
VerificationScreen: { screen: VerificationScreen },
}, {
headerMode: 'none',
})
// Manifest of possible screens
const PrimaryNav = StackNavigator({
drawerStack: { screen: DrawerNavigation },
loginStack: { screen: LoginStack },
}, {
// Default config for all screens
headerMode: 'none',
initialRouteName: 'loginStack',
transitionConfig: noTransitionConfig,
})
export default PrimaryNav
Now we have done a little bit tweak in the first App.js file which will run just after botting the React native application from index.ios.js/index.android.js/index.js file. We just set a state loading to check whether data is loaded from AsyncStorage or not. And if the data is loaded, then we will return our Root component else we will return null, which will not show login screen or anything on the UI front.
import '../Config'
import DebugConfig from '../Config/DebugConfig'
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import RootContainer from './RootContainer'
import createStore from '../Redux'
import { AsyncStorage, Linking } from 'react-native'
import Constants from '../Components/Constants'
import LinkRoutes from '../Config/LinkRoutes';
import {NavigationActions} from 'react-navigation';
// create our store
const store = createStore()
/**
* Provides an entry point into our application. Both index.ios.js and index.android.js
* call this component first.
*
* We create our Redux store here, put it into a provider and then bring in our
* RootContainer.
*
* We separate like this to play nice with React Native's hot reloading.
*/
class App extends Component {
constructor(props) {
super(props)
this.state = {
loading: false,
}
}
componentWillMount() {
AsyncStorage.getItem(Constants.KEY_IS_LOGIN, (err, result) => {
this.setState({ loading: true} , () => {
if (result === '1') {
const navigateAction = NavigationActions.navigate({
routeName: 'drawerStack',
index: 0,
});
store.dispatch(navigateAction);
}
})
});
}
render() {
if(this.state.loading){
return (
<Provider store={store}>
<RootContainer />
</Provider>
)
}else{
return null
}
}
}
// allow reactotron overlay for fast design in dev mode
export default DebugConfig.useReactotron
? console.tron.overlay(App)
: App
In componentWillMount I have just dispatched a NavigationActions that will navigate to the Drawer screen/Home screen. Hope this helps.
@AlpZero thanks for your example but what is disadvantage for using with this way? i mean do you know why some people dislike your solution?
it's because with that solution you will not be able to make a transition between the login screen and the home page, because when the state "userLogged" change to true, the render function of the class "App" will only change one navigator to another. It's a bad solution and deserves all the dislikes xD
@AlpZero thanks i got it, but could you find a better solution? do you know what is the best practice? this is very basic requirement in navigation and it is strange to me why they don't have any documentation for this scenario? :-/
I think the best way is make the setup for integrating react-navigation with redux (https://reactnavigation.org/docs/guides/redux) and make the initial route to a loading screen.
When the app is opened, you make all the login verifications and if the user is logged in or not, you make a navigation action dispatch to the right route.
It's not very well documented, but you can send actions from any location of the app. The boilerplate to an navigate action is: { type: 'Navigation/NAVIGATE', routeName: ' ' }
I agree with @AlpZero , that's actually the approach I use too in my prod app.
If you want another approach, this article we link in the README also provide a way to do it.
Btw if you feel that the docs are not in-depth enough, feel free to submit a PR to them, we'll review it asap :) PRs to Docs are always welcome :)
@AlpZero thanks but i can't understand how integrating with Redux can fix this problem, could you please give me example?
@derakhshanfar I don't know if I can do a good explanation, my english sucks hahauhauh. Let's try. The real fix here is to make the initial route to a loading screen instead of login or home screen, because once you are on such route, you can do a verification of the login state and make the animation for the right route. The integration with Redux is only to do this with a better controllability over the navigator state. I don't know how is your familiarity with redux, but if you used before, you know that is possible to control any state of any component from any location of the app and that is the point. You can make all login verifications in other file using redux-saga, for exemple, and from that other file, make a transition between the loading screen and home screen, separating logic from visual components. It's been a long time since I used react-navigation, I doesn't remember very well. @kelset Do you have another idea to explain why is better do that with redux? Maybe another good scenario to make the redux integration is to control nested navigators, like the one @iamrutvik showed. To be honest with you, in newest projects I doesn't even used a navigation library. I'm making all the transition's between screen's with the Animated API, since with that I have all the controllability that I need, and I can set wich component will be rendered too, all in my hands 😆.
@AlpZero thanks so much dude. first of all you know English better than me :-) . yes i worked with Redux but in my idea the reason of using library is getting easier but unfortunately as you say i think it's better to use native navigation for having all the controllability. maybe for next project because we can't change navigation system for current project right now.
@kelset thanks for reply and making a good library for navigation, but i think the support is very important after release a package, the problem is when i see the source code, i can't understand some part of it. so we have to ask question from contributions and i expect to give a answer because we trust this library that's why we use it in our project.