Search code examples
react-nativereact-navigationreact-native-navigationreact-native-push

React Native get navigation object outside screen component


I need to be able to navigate and reset navigation stack from modules that are not necessarily screen components. It means, I can't use:

const {navigate} = this.props.navigation;

In my case, I need to properly redirect user to the right screen when he taps on push notification. I only have a callback:

onNotification: function(notification) {
    // show correct screen and reset navigation stack
}

I just need more flexibility with navigation. So how can I do it for my case?


Solution

  • Here is my solution. I implemented base class for all screens. With this I always know what screen I am at and can always get navigation object to redirect user whenever needed:

    import React, {Component} from 'react';
    
    export default class Base extends Component {
        static screen;
    
        constructor(props) {
            super(props);
            Base.screen = this; 
        }
    
        nav() {
            return this.props.navigation;
        }
    }
    

    In some other component/module I can just call this to navigate to a different screen:

    Base.screen.nav().navigate(...);