Create Stack Navigator in React-Native And Expo

Wanted:

I want to make navigation between two screen like image below:

stackNavigator

  • If User press Go To Second Screen –> then the screen will changing to Detail
  • If User press Go To First Screen then the screen will changing to Master

Question:

How to make it … ?

Answer:

We will make three screen:

  • FirstScreen.js
  • SecondScreen.js
  • App.js

FirstScreen

Create FirstScreen.js file inside views folder and insert this code:

import React from ‘react’;
import { Text, View, StyleSheet } from ‘react-native’;const FirstScreen = (props) => (

<View style={styles.container}>

<Text onPress={()=>props.navigation.navigate(‘Second’)}
style= {styles.text}>Go To Second Screen –></Text>

</View>

)
const styles = StyleSheet.create({

container: {

flex: 1,
alignItems: ‘center’,

},
text:{

marginTop:10,
color:’blue’

}

})
export default FirstScreen;

Explain:

props.navigation.navigate is a function to go to another screen

 

SecondScreen

Create SecondScreen.js file inside views folder and insert this code:

import React from ‘react’;
import { Text, View, StyleSheet } from ‘react-native’;const SecondScreen = (props) => (

<View style={styles.container}>

<Text onPress={()=>props.navigation.navigate(‘First’)}
style= {styles.text}>Go To First Screen</Text>

</View>

)
const styles = StyleSheet.create({

container: {

flex: 1,
alignItems: ‘center’,

},
text:{

marginTop:10,
color:’red’

}

})
export default SecondScreen;

 

App.js

Modify the App.js content like this code:

import { createStackNavigator, createAppContainer } from ‘react-navigation’;
import React from ‘react’;
import FirstScreen from ‘./views/FirstScreen’;
import SecondScreen from ‘./views/SecondScreen’;const stackNav = createStackNavigator({

First: {

screen: FirstScreen,
navigationOptions: {

title: ‘Master’

},

},
Second: {

screen: SecondScreen,

navigationOptions: {

title: ‘Detail’

},

},
},{headerLayoutPreset: ‘center’});

const App=createAppContainer(stackNav);

export default App;

Explain:

headerLayoutPreset: ‘center’ is used to centering header title

 

Thanks For Reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *