DEV Community 👩‍💻👨‍💻

Cover image for Using React Navigation with Functional Components
Harshil Agrawal
Harshil Agrawal

Posted on • Updated on • Originally published at harshil.dev

Using React Navigation with Functional Components

React Navigation is a popular library used with React Native for navigation. It helps us to build navigational apps. Here is a quick guide for implementing React Navigation with Functional Components.
I have been using react-navigation with Class Components but haven't ever used them with Functional Components. Recently I was working on a small project to learn hooks and came across the issue of using reat-navigation with Functional Component. Unfortunately there was no documentation available on the officail website. I hope this article helps anyone who is looking to setup navigations with functional components.

Note: If you're new to React Navigation, I recommend you to go through their official docs to understand the basics.

Creating A Stack Navigator

Creating a stack navigator is same as that for Class Components. We use the createStackNavigator method and pass objects.

import { createAppContainer, createStackNavigator } from 'react-navigation'

// Importing the screens
import Home from './src/Home'
import Article from './src/Article'

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

const App = createAppContainer(AppNavigator);

export default App;

Enter fullscreen mode Exit fullscreen mode

Create Home Screen (Class Component)

We will create the Home screen by making Class Component to understand the difference.

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

export default class Home extends React.Component {

    static navigationOptions = {
        // Sets the title of the Header
        title: 'Home',
    };

    render () {
        return (
            <View>
                <TouchableOpacity
                    onPress={()=>{this.props.navigation.navigate('Article')}}
                >
                    <Text>Click Here</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

...

Enter fullscreen mode Exit fullscreen mode

To convert this Class component into a Functional Component the most important thing to keep in mind here 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 call the method on the functional component.
The navigation object is passed as a prop.

Create Home Screen (Functional Component)

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

const Home = ({navigation}) =>(
    <View>
        <TouchableOpacity
            onPress={()=>{navigation.navigate('Article')}}
        >
            <Text>Click Here</Text>
        </TouchableOpacity>
    </View>
)

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

...

export default Home
Enter fullscreen mode Exit fullscreen mode

This was a small demo, I hope it will help you!

Top comments (15)

Collapse
rozzz333 profile image
rozzz333

should i install its dependencies?
when i try to install dependencies by this command :

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

i get error

Collapse
harshil1712 profile image
Harshil Agrawal Author

Hey @rozzz333 ,
Are you trying to install it in a new project or in an existing one? Also it might help if you could share the error you're getting.

Collapse
hbwebdev profile image
hb-webdev • Edited on

I don't understand: Is your Home Screen component in a separate .js file? If so, don't you need to import App from './App' so you can use the stack navigator exported from App.js??????????????? Why is this so impossible?? I simply want to navigate between .js files!!!

EDIT: Oh...you're navigating from App.js to Home.js...What if I want to navigate back from Home.js to App.js?? (What if I want the navigation stack accessible in different .js files???)

Collapse
hardikcc profile image
Hardik Shah

How can we use class in react-navigation-5?

Collapse
harshil1712 profile image
Harshil Agrawal Author

Hey Hardik,
Were you able to get it working? Do you want me to write a blog post for this? Please let me know how I can help you.

Collapse
tecants profile image
Techie

yes please make a blog post of react navigation 5 using class components ....if already have blog ....please give link

Thread Thread
harshil1712 profile image
Harshil Agrawal Author

Hey @Techie,
I started writing the blog for it, but later realized that it is similar to the way we did with the previous versions, except for a few minor changes ofcourse. If you need help with that, I'll try to complete is soon, and share the link with you.

Collapse
hardikcc profile image
Hardik Shah

Hi Harshil, I was able to make it work. But a detailed blog will help many developers as no material is available for navigation 5.0.

Collapse
kiwipedro profile image
kiwipedro

Thanks Harshil, that's really helpful. How would you handled setParams to make the header dynamic?

Collapse
corsal8 profile image
Corsal8

Hi! I'm not the OP, but I've made the header dynamic by passing to the Home.navigationOptions function the navigation parameter like so:

Home.navigationOptions = navigation => ({
  title: navigation.navigation.getParam('name', 'John Doe')
});

This should work based on the React Navigation doc (reactnavigation.org/docs/en/header...).

Last but not least, I'm completely new to React Native, so take my answer with a grain of salt :)

Collapse
kiwipedro profile image
kiwipedro

Thanks @corsal8 , not quite what I meant: if you look on the same react-native doc it's the setParam function I'm trying to use. Not sure of the syntax when using it in a functional component compared to the class component that the docs exemplify :)

Collapse
harshil1712 profile image
Harshil Agrawal Author

Hey kiwipedro I am glad that the article could help. To use the setParams() method the structure is similar to navigate() method as shown in the article above, navigation.setParams({...})

Collapse
indavidjool profile image
indavidjool

Thanks mate! I just started converting a small app from class to function components, hit this very obstacle, and fortunately your post got me going again.

Collapse
harshil1712 profile image
Harshil Agrawal Author

Thank you for reading it! I am happy that this could help you. 😄

Collapse
100rabhcsmc profile image
Saurabh Chavan • Edited on

This is super Thank You Bro.

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.