When you are learning react native, the inbuilt navigator of react native is good enough i.e.
http://facebook.github.io/react-native/releases/0.43/docs/navigator.html
and
http://facebook.github.io/react-native/releases/0.43/docs/navigatorios.html
Because while learning we only have to deal with few screens. But, when we move from learning stage to developing professional apps we find the inbuilt navigator quite cumbersome and not very systematic.
Now, there is a good navigation solution available which can be used to keep things tidy. React Navigation (https://www.npmjs.com/package/react-navigation) is a module that makes navigation from screen to screen very systematic, clean, and graceful.
Lets see how to use this module in our application.
First we need to install it using npm install command like this :
npm install react-navigation --save
Next, we can use it in our index file of app like this :
import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import Login from './login' import Home from './home' import {StackNavigator} from 'react-navigation' const RouteConfigs = { Login: {screen:Login}, Home: {screen:Home} } const InvisionApp = StackNavigator(RouteConfigs) AppRegistry.registerComponent('InvisionApp', () => InvisionApp);
Our login.js file looks like this :
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Button } from 'react-native'; export default class Login extends Component { render() { const { navigate } = this.props.navigation return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to Login Screen! </Text> <Text style={styles.instructions}> Press Home button to go to Home screen </Text> <Button onPress={() => navigate('Home')} title="Home" /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
And, our home.js file looks like this
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class Home extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to Home Screen! </Text> <Text style={styles.instructions}> Press Back button to go back </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
Here is the demo of above code: