In this post we will learn how to NAVIGATE using ALERT BOX in react native
import React from 'react';
import {Alert ,StyleSheet, Text, View,TouchableOpacity } from 'react-native';
import {createStackNavigator,createTabNavigator,createDrawerNavigator,withNavigation,NavigationAction,NavigationActions,DrawerNavigator,StackNavigator } from 'react-navigation';
/*
This is our second Screen
*/
class Screen2 extends React.Component{
static navigationOptions={
title:'',
header:null,
}
render(){
return(
<View style={styles.container}>
<Text>this is screen 2</Text>
</View>
);
}
}
//end of screen 2
/*
this is our home screen
here we create a touchableopacity which on pressing opens a ALERT box(_onpressButton(function))
and on pressing OK we navigate to our SCREEN2
and on pressing CANCEL we stay on the same page
*/
class Screen1 extends React.Component{
static navigationOptions={
title:'',
header:null,
}
_onpressButton=()=>{ //on preesing verify 'touchable opacity' on home screen
Alert.alert
(
'Alert box',
'Click on OK to move to other Screen2 click CANCEL to stay on the same page',
[
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), },
{text: 'OK', onPress: this._onNavigate.bind(this) },
],
{ cancelable: false }
)
}
_onNavigate(){
const navigateAction = NavigationActions.navigate({
routeName: 'Stwo',
params: {},
action: NavigationActions.navigate({ routeName: 'SubProfileRoute' }),
});
this.props.navigation.dispatch(navigateAction);
}
render(){
return(
<View style={styles.container}>
<TouchableOpacity onPress={this._onpressButton.bind(this)} >
<View style={{ marginBottom: 30, width: 290, alignItems: 'center',backgroundColor:'rgb(169,36,8)'}} >
<Text style={{padding: 20,color: 'white'}}>Click me</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
//end of screen 1
//Style sheet
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
//end of style sheet
//routes
const RootStack =createStackNavigator(
{
Sone:Screen1,
Stwo:Screen2,
},
{
initialRouteHome:'Sone',
},
{
},
);
//end of routes
//main function
export default class App extends React.Component
{
render(){
return(
<RootStack />
);
}
}
OUTPUT:
FIG(1) FIG(2) FIG(3)
In FIG(1) we see our touchable opacity
In FIG(2) we have our ALERT box with Buttons OK and CANCEL
In FIG(3) we navigate to our screen 2 by pressing OK