React Native Open Navigate to Another Activity on Button Click

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.

Screenshot of Command Prompt after installing the library :

4. Now open your project’s index.ios.js or index.android.js file and Import AppRegistry, StyleSheet, Text, View and Button component in your project.

5. Import StackNavigator module from react-navigation library in your project.

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.

7. Create another class named as SecondActivity .

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.

9. Add all below CSS classes.

10. Complete source code for App.js File :

Screenshot in Android Mobile Phone application :

Navigate

Screenshot in iOS iPhone mobile application :

33 Comments

  1. 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.

  2. 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

  3. 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 }
      });

  4. Thanks for your help. It worked 🙂

  5. where i need write step 8 in which file??

  6. 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.

  7. 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

  8. i have sent it.pls check

  9. i just wanted to call another class from one class

  10. 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:

  11. 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.

  12. I’m facing the error: undefined is not an object (evaluating ‘e.props.navigation’)
    Please tell me what should i need to do.

  13. 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 ?

  14. 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.

  15. 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!.

  16. 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.

Leave a Reply

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