In this tutorial you will learn how we can use Stack Navigator in React native.
react-native run-android or react-native run-ios
Step 2: to work with react navigation you have to install react-navigation npm package.
run a new Command:
Install with NPM
npm install --save react-navigation
Install with Yarn
yarn add react-navigation
Step 3: open project folder create new folder "pages". inside pages folder create new file name "app.js".
copy code and paste in your app.js
import React, { Component } from 'react';
import { AppRegistry,View,Text,StyleSheet } from 'react-native';
import { StackNavigator } from 'react-navigation';
import HomeScreen from './home';
import Products from './products';
const nativeShop = StackNavigator({
Home: { screen: HomeScreen },
Products: { screen: Products },
});
export default nativeShop;
now you need to create home.js and products,js inside pages folder.
home.js
import React, { Component } from 'react';
import { AppRegistry,View,Text,StyleSheet
,Button,TouchableOpacity } from 'react-native';
export default class home extends Component{
static navigationOptions = {
title: 'Welcome',
};
render(){
const { navigate } = this.props.navigation;
return(
<View style={{display:'flex',alignItems:'center', justifyContent:'center'}}>
<Text style={{margin:10,fontWeight:'bold',color:'#000'}}>Hello from home</Text>
<TouchableOpacity
style={styles.cat}
onPress={() => navigate('Products', {cat:'electronics'})}
><Text Text style={{color:'#fff'}}>Electronics ></Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.cat}
onPress={() => navigate('Products', {cat:'automobiles'})}
><Text Text style={{color:'#fff'}}>Automobiles ></Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.cat}
onPress={() => navigate('Products', {cat:'Movies'})}
><Text Text style={{color:'#fff'}}>Movies ></Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.cat}
onPress={() => navigate('Products', {cat:'Books'})}
><Text Text style={{color:'#fff'}}>Books ></Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
cat:{
backgroundColor:'blue',
padding:10,margin:10,width:'95%'
}
})
AppRegistry.registerComponent('home', () => home);
products.js
import React, { Component } from 'react';
import { AppRegistry,View,Text,StyleSheet } from 'react-native';
export default class products extends Component{
static navigationOptions = {
title: 'Products',
};
render(){
const { params } = this.props.navigation.state;
return(
hello from products
{params.cat}
);
}
}
const styles = StyleSheet.create({
})
AppRegistry.registerComponent('products', () => products);