Chandan Rajpurohit

An Artist With Technical Skills

Navigation in mobile application is important as it gives authority to user to change screen on-click. To achieve navigation in React Native we can use React Navigation.

React Navigation Logo
React Navigation

Getting started | React Navigation

React Navigation is a popular library used with React Native for navigation.

Let’s understand how to implement React Navigation with Class Components and Functional Components.

Creating A Stack Navigator

Creating a stack navigator is same in both Class as well as Functional Components i.e., we have to use the createStackNavigator from react-navigation method and pass objects.

import { createAppContainer, createStackNavigator } from "react-navigation"
import Home from "./src/Home"
import Blog from "./src/Blog"

const AppNavigator = createStackNavigator({
    Home: {screen: Home},
    Blog: {screen: Article},
    },
    {
        // Initial Screen
        initalRoute: "Home"
    }
);

const App = createAppContainer(AppNavigator);

export default App;

Create Home Screen (Class Component)

Implementation of Home Screen using Class Component

import React from "react"
import { View, Text, TouchableOpacity } from "react-native"

export default class Home extends React.Component {

    static navigationOptions = {
        title: "Home",
    };

    render () {
        return (
            <View>
                <TouchableOpacity
                    onPress={()=>{this.props.navigation.navigate("Blog")}}
                >
                    <Text>Blog</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

Now to achieve above in a Functional Component the most important thing to keep in mind is that navigationOptions is a static method.

Static methods aren’t called on instances of the class. Instead, they’re called on the class itself.

Since we can’t create instances of Functional Components, we will create the method and pass navigation object as a prop in it.

Create Home Screen (Functional Component)

import React from "react"
import { View, Text, TouchableOpacity } from "react-native"

const Home = ({navigation}) =>(
    <View>
        <TouchableOpacity
            onPress={()=>{navigation.navigate("Blog")}}
        >
            <Text>Blog</Text>
        </TouchableOpacity>
    </View>
)

Home.navigationOptions = () => {(
    title:"Home"
)}

export default Home

Note: – In Class Component this.props.navigation.navigate(“Blog”) and In Functional Component navigation.navigate(“Blog”)

React Navigation | React Navigation

Creating a New Application in React Native – Chandan Rajpurohit

Thank you for reading this article, I really appreciate it. Let me know in case of any queries in the comment section.


Leave a Reply

%d bloggers like this: