Xiiryo
Xiiryo

Reputation: 3257

Adding a back button for each bottom tab with React Navigation

The bottom tabs navigation is looking something like that:

const Tab = createBottomTabNavigator();

export default function TabStackScreen() {
    return (
        <Tab.Navigator initialRouteName="Home">
            <Tab.Screen name="Home" component={HomeStackScreen} />
            <Tab.Screen name="Favorites" component={FavoritesStackScreen} />
            <Tab.Screen name="Search" component={SearchStackScreen} />
        </Tab.Navigator>
    )
}

There is not back button on the favorites and search screen. I guess this is the normal behavior, but I would love to have one.

I did not find something relevant in the doc, except recreating a component that looks like the native back button and adding it on some screens using headerLeft. Is there a more simple method?

Upvotes: 1

Views: 3199

Answers (1)

Guilherme Andrade
Guilherme Andrade

Reputation: 91

In my projects I like to create custom headers, and I do not show the default header and show my own custom header component.

On my custom component I add right and left components, and let the screens decide what to do, by default the back button is shown, but if the screen pass the noBack property, the button is hidden.

You can also add a right component, for example a close button.

That is what I use to do:

const screenOptions = {
  headerShown: false
};


<RootStack.Navigator screenOptions={screenOptions} mode="modal">

and then create my own component

export const Header = ({ title, leftComponent, rightComponent, noBack }) => {
  const navigation = useNavigation();

  return (
    <Wrapper>
      {leftComponent ||
        (noBack ? (
          <Placeholder />
        ) : (
          <Button
            onPress={() => navigation.goBack()}
            accessible
            accessibilityRole="button"
            accessibilityLabel="Back">
            <Icon
              size={30}
              name={Platform.OS === 'android' ? 'arrow-left' : 'chevron-left'}
            />
          </Button>
        ))}
      <Title bold accessibilityRole="header" acessible acessibilityText={title}>
        {title}
      </Title>
      {rightComponent || <Placeholder />}
    </Wrapper>
  );
};

Doing that, you are able to customize everything on your header, it works like a charm for me.

Upvotes: 2

Related Questions