Search code examples
react-nativeeventsnavigationfocus

NavigationEvents in react-native navigation-6


Hi I am trying to implement Navigation but I am keep getting the error

Invariant Violation: withNavigation can only be used on a view hierarchy of a navigator. The wrapped component is unable to get access to navigation from props or context.

Here is my code this works for previous version of react-navigation

import { View, StyleSheet, Text } from "react-native"
import { NavigationEvents } from 'react-navigation';


const Home = (props) =>{
   
    return (<View>
        <NavigationEvents
                onWillFocus={()=>{
                  console.log("onwillfocus")
                }}
                onDidFocus={() =>{
                   console.log("onDidFocus")
                  }}
            />
        <Text>Hello world</Text>
    </View>)
}

export default Home

Solution

  • In case you need to detect if the screen is focused, React Navigation 6 expose a simple useIsFocused hook - https://reactnavigation.org/docs/use-is-focused/