This tutorial is the second part of Add New Activity in React Native Application tutorial. In this tutorial we would going to create an react native application with 2 different activities, First one is MainActivity and Second is SecondActivity. Now we would add a button in our MainActivity and on button onPress – onClick event we would call a function that will navigate us to SecondActivity.
Contents in this project Open Navigate to Another Activity on Button Click in React Native App :
1. Start a fresh React Native project. If you don’t know how then read my this tutorial.
2. Read our Previous tutorial to Add New Activity in Existing React Native Project.
3. Import react-navigation library in your project using using NPM server. So open your project’s folder in Command Prompt / Terminal and Type below command to install react-navigation library.
1 |
npm install --save react-navigation |
Screenshot of Command Prompt after installing the library :
1 2 3 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Button } from 'react-native'; |
5. Import StackNavigator module from react-navigation library in your project.
1 |
import { StackNavigator } from 'react-navigation'; |
6. Create a new class named as MainActivity.
static navigationOptions : Used to set the Activity screen title shown inside the Title bar.
FunctionToOpenSecondActivity : This function allow us to navigate to the Second Activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class MainActivity extends Component { static navigationOptions = { title: 'MainActivity', }; FunctionToOpenSecondActivity = () => { this.props.navigation.navigate('Second'); } render() { return( <View style = { styles.MainContainer }> <View style={{marginBottom: 20}}> <Text style = { styles.TextStyle }> This is MainActivity </Text> </View> <Button onPress = { this.FunctionToOpenSecondActivity } title = 'Click Here To Open Second Activity'/> </View> ); } } |
7. Create another class named as SecondActivity .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class SecondActivity extends Component { static navigationOptions = { title: 'SecondActivity', }; render() { return( <View style = { styles.MainContainer }> <Text style = { styles.TextStyle }> This is SecondActivity </Text> </View> ); } } |
8. Add StackNavigator method with your Application project name to call the activities like i did in below code. For example my project name is Project. This step is very important.
1 2 3 4 5 6 |
export default Project = StackNavigator( { First: { screen: MainActivity }, Second: { screen: SecondActivity } }); |
9. Add all below CSS classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const styles = StyleSheet.create( { MainContainer: { justifyContent: 'center', flex:1, margin: 10 }, TextStyle: { fontSize: 23, textAlign: 'center', color: '#000', }, }); |
10. Complete source code for App.js File :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Button } from 'react-native'; import { StackNavigator } from 'react-navigation'; class MainActivity extends Component { static navigationOptions = { title: 'MainActivity', }; FunctionToOpenSecondActivity = () => { this.props.navigation.navigate('Second'); } render() { return( <View style = { styles.MainContainer }> <View style={{marginBottom: 20}}> <Text style = { styles.TextStyle }> This is MainActivity </Text> </View> <Button onPress = { this.FunctionToOpenSecondActivity } title = 'Click Here To Open Second Activity'/> </View> ); } } class SecondActivity extends Component { static navigationOptions = { title: 'SecondActivity', }; render() { return( <View style = { styles.MainContainer }> <Text style = { styles.TextStyle }> This is SecondActivity </Text> </View> ); } } export default Project = StackNavigator( { First: { screen: MainActivity }, Second: { screen: SecondActivity } }); const styles = StyleSheet.create( { MainContainer: { justifyContent: 'center', flex:1, margin: 10 }, TextStyle: { fontSize: 23, textAlign: 'center', color: '#000', }, }); |
Screenshot in Android Mobile Phone application :
Screenshot in iOS iPhone mobile application :
Hi admin,
I am facing the same issue here which i got in login screen activity tutorial.
It is giving export error.
i have given default export in the line :-
export default const Project = StackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
now it is giving syntax error.
Hitesh you need to remove the const from export default const Project = StackNavigator line. I have updated the code. You can see above.
when ever i add billow code I get error but when I remove it no error come
export default firstapp = StackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
my full App.js code
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from ‘react’;
import { StackNavigator } from ‘react-navigation’;
import {
Platform,
AppRegistry,
StyleSheet,
Text,
Button,
Alert,
View
} from ‘react-native’;
const instructions = Platform.select({
ios: ‘Press Cmd+R to reload,\n’ +
‘Cmd+D or shake for dev menu’,
android: ‘Double tap R on your keyboard to reload,\n’ +
‘Shake or press menu button for dev menu’,
});
export default class App extends Component {
static navigationOptions =
{
title: ‘MainActivity’,
};
_onPress() {
Alert.alert(‘on Press!’);
}
onPressLearnMore(){
this.props.navigation.navigate(‘Second’);
}
render() {
return (
Welcome toss wht
To get started, edit App.js
);
}
}
class SecondActivity extends Component
{
static navigationOptions =
{
title: ‘SecondActivity’,
};
render()
{
return(
This is SecondActivity
);
}
}
export default firstapp = StackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
backgroundColor: ‘#f3f3f3’,
margin:10,
},
welcome: {
fontSize: 3,
textAlign: ‘left’,
},
instructions: {
textAlign: ‘center’,
color: ‘#111111’,
marginBottom: 1,
},
});
AppRegistry.registerComponent(‘firstapp’, () => firstapp);
error
Nisarg you need to remove export default keyword from export default class App extends Component.
Thanks it’s working now!! can you please explain what does “export default” indicate ?
Nisarg export default tells the react native compiler to load this section of code first and also it is the main code.
Sir hame kya alag alag file create karna hoga … ya ek hi file me coding aai gi
Ek hi file me sari coding aa jaegi.
Hi, it is very nice tutorial for beginers. I followed your code and implemented on mine for the navigation. But I’m getting error as “Can’t find variable: FirstActivity”
I mentioned my code below:
import React from ‘react’;
import { StyleSheet,View,Image, Text,ImageBackground, TextInput, Button, Alert} from ‘react-native’;
import { StackNavigator } from ‘react-navigation’;
class HomeScreen extends React.Component {
static navigationOptions=
{
title: ‘Login’,
};
FunctionToOpenRegistration = () =>
{
this.props.navigation.navigate(‘Registeration’);
}
SampleFunction1(){
Alert.alert(“Function Without Argument”);
}
constructor(props) {
super(props);
this.state = {
username: ”,
pasword: ”
};
}
render() {
return (
LOGIN
Enter your credentials here
Username
this.setState({username})}
value = {this.state.username}
underlineColorAndroid = ‘rgba(0,0,0,0)’/>
Password
this.setState({pasword})}
value = {this.state.pasword}
underlineColorAndroid = ‘rgba(0,0,0,0)’/>
this.FunctionToOpenRegistration}/>
Don’t have an account?
SIGN UP
);
}
}
class Registeration extends React.Component {
static navigationOptions =
{
title: ‘Register’,
};
render()
{
return (
LOGIN
Enter your credentials here
);
}
}
export default BttonWork = StackNavigator(
{
HomeScreen: { screen: FirstActivity },
Registeration: { screen: SecondActivity }
});
Neeraj you need to remove HomeScreen and Registration from export default BttonWork and here set below code, This should work fine 🙂 .
export default BttonWork = StackNavigator(
{
First: { screen: HomeScreen },
Second: { screen: Registeration }
});
Thanks for your help. It worked 🙂
Welcome Neeraj 🙂 .
where i need write step 8 in which file??
In App.js file .
I am using stack navigator to show header on all pages. I imported the header section in this page. The problem is now I am getting two headers. How to remove the header showing up on this page and keep only the imported header title.
Melvin read my this tutorial to hide the navigation bar header https://reactnativecode.com/hide-activity-navigation-bar/ .
This is my code below
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, Text, FlatList, View,TouchableOpacity, Button, Navigator } from ‘react-native’;
import { StackNavigator } from ‘react-navigation’;
class MainApp extends Component {
static navigationOptions =
{
title: ‘MainApp’,
};
state={
data:[]
};
componentDidMount() {
this.fetchData();
}
fetchData=async() =>{
const response=await fetch(“http://adityaimagingit.com/aiit/API/Reffernce.aspx”);
const json=await response.json();
this.setState({data:json});
};
render()
{
return(
This is first page.
i}
renderItem={({item}) =>
{item.ar_name}
}
/>
);
}
FunctionToOpenSecondActivity = () => {
this.props.navigator.push(‘Second’);
}
}
export default firstapp = StackNavigator(
{
First: { screen: MainApp },
Second: { screen: SecondActivity }
});
class SecondActivity extends Component
{
static navigationOptions =
{
title: ‘SecondActivity’,
};
render()
{
return(
This is Second Page.
);
}
}
const styles = StyleSheet.create(
{
container:
{
background:’#000000′,
},
TextStyle:
{
fontSize: 23,
textAlign: ‘center’,
background: ‘#FFFFFF’,
},
buttonText:{
color:’#3498db’,
fontSize:16,
fontWeight:’500′,
textAlign:’center’
}
});
error
What error you have facing ??
Module AppRegistry is not a registered callable module is error
Akhil in comment the code is not showing correctly send us your code on [email protected]
i have sent it.pls check
i just wanted to call another class from one class
This is in my app.js file.
import React, { Component } from ‘react’;
import {View, Text, StyleSheet, TextInput,TouchableOpacity} from ‘react-native’;
import styled from “styled-components/native”; // Version can be specified in package.json
import Carousel from ‘react-native-snap-carousel’; // Version can be specified in package.json
import HeaderCustom from ‘./src/supportFiles/codeFiles/headerCustom’;
import {StackNavigator} from ‘react-navigation’;
import CardDeck from ‘./src/supportFiles/codeFiles/cardDeck’;
class ThumbnailCarousel extends Component {
static navigationOptions =
{
title: ‘ThumbnailCarousel’,
};
FunctionToOpenSecondActivity = () =>
{
this.props.navigation.navigate(‘Second’);
}
constructor(props){
super();
this.state = {
numberValue: ’01’
}
this.state = {
errors: []
}
this.props = props;
this._carousel = {};
this.init();
}
init(){
this.state = {
videos: [
{
id: “WpIAc9by5iU”,
thumbnail: require(‘./first.png’),
title: “Create your own group of words.”
}, {
id: “sNPnbI1arSE”,
thumbnail: “file:///Users/chandnisharma/Downloads/AWT/NewPsw/src/supportFiles/img/second.png”,
title: “These are the most common words found in the children’s books.”
}, {
id: “VOgFZfRVaww”,
thumbnail: “file:///Users/chandnisharma/Downloads/AWT/NewPsw/src/supportFiles/img/third.png”,
title: “These words are used to describe an action.”
}
],
};
console.log(“ThumbnailCarousel Props: “, this.props)
}
_renderItem = ( {item, index} ) => {
console.log(“rendering,”, index, item)
return (
{
console.log(“clicked to index”, index)
this._carousel.snapToItem(index);
}}
>
{item.title}
Move to next View
{/**/}
);
}
render = () => {
console.log(“videos: updating”)
return (
{ this._carousel = c; } }
data={this.state.videos}
renderItem={this._renderItem.bind(this)}
onSnapToItem={this.handleSnapToItem.bind(this)}
sliderWidth={360}
itemWidth={290} //256
layout={‘default’}
firstItem={0}
/>
);
}
}
export default NewPsw = StackNavigator(
{
First: { screen: ThumbnailCarousel },
Second: { screen: CardDeck }
});
//const { width, height } = Dimensions.get(‘window’); // cs
const VideoTitleText = styled.Text
color: white;
justify-content: center;
const CurrentVideoImage = styled.Image
width: 290;
height: 500;
border-radius: 20;
;
const ThumbnailBackgroundView = styled.View
justify-content: center;
align-items: center;
width: 290;
height: 500;
;
const CurrentVideoTO = styled.TouchableOpacity
;
const CarouselBackgroundView = styled.View
height: 100%;
width: 100%;
;
const styleText = StyleSheet.create({
textTopNumber: {
top: -10,
color: ‘gray’,
fontWeight: ‘500’,
fontSize: 20,
height: 20,
},
textCardTitle: {
top: -10,
color: ‘white’,
fontWeight: ‘500’,
fontSize: 20,
height: 20,
},
textCardDetail: {
color: ‘white’,
fontWeight: ‘300’,
fontSize: 20,
height: 70,
alignItems:’center’
},
viewProp:
{ position: ‘absolute’,
aspectRatio: 1,
top: 0,
left: 10,
right: 10,
height: 400,
alignItems: ‘center’,
justifyContent: ‘center’,
},
});
const stylesButton = StyleSheet.create({
button: {
borderColor: “gray”,
borderRadius: 20,
padding: 10,
// marginBottom: 20,
shadowColor: ‘#303838’,
shadowOffset: { width: 0, height: 5 },
// shadowRadius: 10,
shadowOpacity: 0.35,
},
});
In my second class
class CardDeck extends Component {
static navigationOptions =
{
title: ‘CardDeck’,
};
}
Error:
Hi,
What will be th project structure (where to create new activity in project path), like in Android we create new activity in project-dir/android/app/src/java/MainActivity.java.
Mayur read our this tutorial this would help your : https://reactnativecode.com/load-call-external-local-js-file/
I’m facing the error: undefined is not an object (evaluating ‘e.props.navigation’)
Please tell me what should i need to do.
Did you install the react navigation library correctly ?
Hello, I want to transition to a new screen, not a screen with back button, (not with a navigation), Do you have a idea about how to do this? Thank you..
Chans you want to navigate to next screen but you want to close the previous screen and then want to move to next screen so on the next screen there will be no back button and if you press the back button then the app will close , Am i right ?
hello sir, I have created two screens but now i want to navigate between screens by clicking on touchable opacity. could you send me the code to navigate between screens that i already created
Amandeep you can set click listener on touchable opacity and call a function on button click from which you can easily navigate to next activity.
Hi,
This is an ok and good tutorial for beginner learning. But we expecting code for which file this code like File name APP.Js Mention top of your screenshot. I hope this is valuable information for you. If you interested this information please consider this or don’t consider.
Thank you!.
Thanks for your suggestion Karthink 🙂 .
Hi,
Thanks for the Tutorial. It helped to me but I have one question.
In my code, there are two default export. Program is giving a error like this: “Only one default export allowed per module.” Can you explain why? Do you have any solution?
Thank you.
Enes because by default in react native it can only support 1 export default in single file .