Let’s use React Navigation to build a simple application for Android and iOS.
Step 1: Firstly, install the react native cli on your machine by using the below command.
#Install React cli npm install -g react-native-cli # Create a new React Native App react-native init SimpleMobileApp cd SimpleMobileApp
Now, you are ready to start adding stuff for the page navigation in React native components
Step 2: For page navigation, we have to install npm dependency react-navigation
# Install the latest version of react-navigation from npm npm install --save react-navigation
Step 3: copy the below code to App.js (Note: In case, if you don`t find your App.js, copy to your default component which loads the application)
import React from 'react'; import { StyleSheet, Text, View, Button } from 'react-native'; import { StackNavigator } from 'react-navigation'; import {FirstComponent} from "./components/FirstComponent"; import {SecondComponent} from "./components/SecondComponent"; class HomeScreen extends React.Component { static navigationOptions = { title: 'Welcome', }; render() { const { navigate } = this.props.navigation; return ( <View> <Text>Hello, Chat App!</Text> <Button onPress={() => navigate('First', { user: 'Lucy' })} title="Go to First" /> <Button onPress={() => navigate('Second', { user: 'Lucy' })} title="Go to Second" /> </View> ); } } const SimpleApp = StackNavigator({ Home: { screen: HomeScreen }, First: { screen : FirstComponent}, Second: { screen : SecondComponent} }); export default class App extends React.Component { render() { return <SimpleApp />; } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' } });
Step 4: Create a Component name FirstComponent.js and add the below code to the component.
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; export class FirstComponent extends React.Component { static navigationOptions = { title: 'Welcome', }; render() { const { params } = this.props.navigation.state; return ( <View> <Text>Welcome {params.user}</Text> <Text>This is First React Native component</Text> </View> ); } }
Step 5: Create another component SecondComponent.js and add the below code to the component
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; export class SecondComponent extends React.Component { static navigationOptions = { title: 'Welcome', }; render() { const { params } = this.props.navigation.state; return ( <View> <Text>Welcome {params.user}</Text> <Text>This is Second React Native component</Text> </View> ); } }
Step 6: Now run the application using the command. You can see the output either expo app or install on the physical device.
# Run the app $ react-native run-android # or: $ react-native run-ios
Download the code from github