How to type Tab Navigator in react navigation 5 and TypeScript

Viewed 1885
import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import {
  BottomTabNavigationProp,
  createBottomTabNavigator,
} from '@react-navigation/bottom-tabs';
import { TabNavigationState } from '@react-navigation/native';


export type RootParamList = {
  Feed: undefined;
  Search: undefined;
};

export enum Screens {
  FEED = 'Feed',
  SEARCH = 'Search',
}
const Tabs = createBottomTabNavigator<RootParamList>();

export interface TabbarProps {
  navigation: BottomTabNavigationProp<RootParamList, Screens>;
  state: TabNavigationState<RootParamList>;
}

const TabBar = (props: TabbarProps) => {
  const handleTabPress = ({
    name,
    isCurrentTab,
  }: {
    name: keyof RootParamList;
    isCurrentTab: boolean;
  }) => {
    if (!isCurrentTab) {
      props.navigation.navigate(name);
    }
  };
  return (
    <View>
      {props.state.routes.map((route, index) => {
        const buttonText = route.name;
        const isCurrentTab = props.state.index === index;
        return (
          <TouchableOpacity
            key={index}
            onPress={() => handleTabPress({ name: route.name, isCurrentTab })}>
            <Text>{buttonText}</Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );
};

const Nav = () => (
  <Tabs.Navigator
    tabBar={({ navigation, state }) => (
      <TabBar navigation={navigation} state={state} />
    )}>
    <Tabs.Screen name={Screens.FEED} component={View} />
    <Tabs.Screen name={Screens.SEARCH} component={View} />
  </Tabs.Navigator>
);

export default Nav;

There is an issue with <Tab.Navigator /> and the tabbar prop. I can't seem to type it correctly for my specific navigation and state props.

enter image description here

2 Answers

You can type your custom component with the BottomTabBarProps and eventually your custom props.

import { BottomTabBarProps } from '@react-navigation/bottom-tabs/src/types'

const TabBar: React.FC<BottomTabBarProps /* & CustomProps */> = ({ state, descriptors, navigation }) => {
...
}

Late to answer, even I was stuck with the same issue, following changes helped me,

Please note I have used type instead of interface, interface will also work.

In your TabBar,

Instead of

export interface {
  navigation: BottomTabNavigationProp<RootParamList, Screens>;
  state: TabNavigationState<RootParamList>;
}

Use

type TabbarProps = {
  navigation: NavigationHelpers<ParamListBase, BottomTabNavigationEventMap>;
  state: TabNavigationState<ParamListBase>;
};

Related