How to Create a Navigator without Back Actions in React Native
Update: This tutorial is outdated. I suggest you check out the authentication flow from the official documentation.
While creating an authentication flow we usually don’t want the screens to navigate back. In such situations, we want a navigator which resets the navigation history while navigating. In this blog post, I will show you how to create a navigator without navigation history in React Native.
Most of the react native projects out there prefer react-navigation library for navigation purposes. Hence, I am also using the same library in this react native example. You can install react navigation library using the instructions given here.
React Navigation library has createSwitchNavigator which shows only one screen at a time. It resets the routes while navigating and you can’t do back actions. Go through the following react native example for a better idea.
App.js
import { createSwitchNavigator, createAppContainer } from "react-navigation";
import Home from './src/Home';
import Sample from './src/Sample';
const AppNavigator = createSwitchNavigator({
Home: {
screen: Home
},
Sample: {
screen: Sample
}
});
export default createAppContainer(AppNavigator);
Home.js
import React, { Component } from 'react';
import { View, Button, StyleSheet } from 'react-native';
class Home extends Component {
constructor(props){
super(props);
}
componentDidMount(){
}
render() {
return (
<View style={styles.container}>
<Button title='Press to Navigate'
onPress={()=>this.props.navigation.navigate('Sample')}></Button>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
}
});
export default Home;
Sample.js
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class Sample extends Component {
constructor(props){
super(props);
this.state = {
data:''
}
}
componentDidMount(){
}
render() {
return (
<View style={styles.container}>
<Text>'Now try to go back!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
});
export default Sample;
Check the output of the example in the gif file given below.
As you see in the output, I have two screens named Home and Sample. I navigate to Sample screen from Home screen. Now, pressing the back button of the device doesn’t navigate back to the former screen.