Routing
We suggest using React Navigation
Installation
Read React Navigation's installation guide
! Pay attention to the native code that needs to be added in Android
Authentication flow
Most of the apps have a login screen. When an already logged in user opens the app, we don't want him to first see the login screen, which checkes whether he's authenticated or not, and the navigate him to the app.
For this, we'll use a switchNavigator.
This is going to be our main entry-point to the app:
import { createSwitchNavigator, createAppContainer } from 'react-navigation';
import Auth from 'src/components/auth/auth';
import Login from 'src/components/navigators/login';
import App from 'src/components/navigators/app';
const Main = createSwitchNavigator({
Auth,
Login,
App
}, {
initialRouteName: 'Auth'
});
export default createAppContainer(Main);
The initialRouteName will navigate the user to the Auth screen, which will check in componentDidMount whether the user is authenticated or not:
import React from 'react';
import { connect } from 'react-redux';
class Auth extends React.Component {
componentDidMount() {
const { user } = this.props;
this.props.navigation.navigate(user ? 'App' : 'Login');
}
render() {
return null;
}
}
const createMapStateToProps = (initialState) => {
const { user } = initialState;
return () => ({
user
});
};
export default connect(createMapStateToProps)(Auth);
You can return null, or add an animation/image that's showing while the navigation is happening. But returning null works great, as it happens so fast the user won't notice anything.
