3

Material Bottom Tab Navigator has the option TabBarBadge to show a little badge (string or number) on the tab icon (like a notification). But in Top Tab Bar Navigator, this option does not exist.

In Top Tab Bar Navigator there is an option called TabBarPosition to set the position of the tab bar on top or bottom. But in Bottom Tab Navigator, this options does not exist ...

So I'm looking for a way to have Badges on my Material Top Tab Bar, or to set the position of my Material Bottom Tab Bar to the top and be able to use TabBarBadge.

Thanks you !

timarceus
  • 31
  • 2

1 Answers1

0

I faced this problem too.This property is really not available until now (although the issue on github opened almost a year ago), so the only solution I have found is to try reinvent the wheel.

So my solution is to create a custom component.

import {MaterialTopTabBarProps} from '@react-navigation/material-top-tabs';

const CustomTabBar:React.FC<MaterialTopTabBarProps> = ({state, descriptors, navigation}) => {
    return (
        <View style={{ flexDirection: 'row', paddingTop: 20, backgroundColor: 'rgb(0,0,0)' }}>
          {state.routes.map((route, index) => {
            const 
                {options} = descriptors[route.key],
                isFocused = state.index === index,
                label =
                    options.tabBarLabel !== undefined
                    ? options.tabBarLabel
                    : options.title !== undefined
                    ? options.title
                    : route.name,
                badge = '1' // You can get this value using your api or something

            return (
                <Text
                    style={isFocused ? {opacity: 1, color: 'rgb(255,255,255)'} : {opacity: 0.5, color: 'rgb(255,255,255)'}}
                    onPress={() => {
                        navigation.navigate(route.name);
                    }}
                >
                    {label}
                    {badge ? <Text>{badge}</Text> : null}
                </Text>
            );
          })}
        </View>
      );
}
  
const Tab = createMaterialTopTabNavigator();

export const MainPage = ({navigation}: MainPageProps) =>{
    return (
        <Tab.Navigator
            tabBar = {(props:MaterialTopTabBarProps) => {
                return(
                    <CustomTabBar {...props} />
                );
            }}
        >
            <Tab.Screen name="Chats" component={ChatsScreen}/>
            <Tab.Screen name="Albums" component={AlbumsScreen} />
        </Tab.Navigator>
    );
}
Oleg
  • 49
  • 1
  • 6
  • You don't need stuff like `:MaterialTopTabBarProps`, `:React.FC` if you using JavaScript instead of TypeScript – Oleg Jun 16 '21 at 22:36