Home > front end >  navigation.goBack function not working in React Native
navigation.goBack function not working in React Native

Time:09-22

StackRoutes.tsx Component (used in App.tsx)

  export const StackRoutes = () => {
  const Stack = createNativeStackNavigator()

  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName={Path.introductionScreen}>
        <Stack.Screen
          name={Path.onBoardingChooseAliasScreen}
          options={Options.onBoardingChooseAliasScreen}
          component={OnBoardingChooseAlias}
        />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

Options.tsx component (being used in StackRoutes.tsx)

import React from 'react'
import { NativeStackNavigationOptions } from '@react-navigation/native-stack'
import { CustomBackButton } from './CustomBackButton'
const onBoardingChooseAliasScreen: NativeStackNavigationOptions = {
   headerLeft: () => { return <CustomBackButton />} 
}
export default {
  onBoardingChooseAliasScreen,
}

CustomBackButton.tsx component (being used in Options.tsx)

import React from 'react'
import styled from 'styled-components/native'
import SVGimg from 'src/shared/images/greenMarker.svg'

export const CustomBackButton: React.FC<any> = ({ navigation }) => {
  return (
    <Wrapper onPress={() => navigation.goBack()}>
      <SVGimg />
    </Wrapper>
  )
}

const Wrapper = styled.Pressable``

The CustomBackButton gets displayed as desired, but the goBack() function doesnt work. If i use default back button it works, so i know there is a stack to fall back on.

How do I make the goBack function work?

CodePudding user response:

It seems like CustomBackButton does not have access to navigation

can you try with useNavigation hook

import React from 'react'
import styled from 'styled-components/native'
import SVGimg from 'src/shared/images/greenMarker.svg'
import { useNavigation } from '@react-navigation/native';

export const CustomBackButton: React.FC<any> = () => {
  const navigation = useNavigation()
  return (
    <Wrapper onPress={() => navigation.goBack()}>
      <SVGimg />
    </Wrapper>
  )
}

const Wrapper = styled.Pressable``
  • Related