How do you change active tab color using Tab.Navigator screenOptions?

37 views Asked by At

I am using React Native, specifically createMaterialTopTabNavigator from React Navigation. I want the tabs to work so that when you press on a tab, it turns a purple color while the other inactive tabs are gray. I was wondering if this is possible using the screenOptions prop, or if I have to create a custom tab bar.

This is my current code:

function CarouselTabs() {
  return (
    <Tab.Navigator
      screenOptions={{
        swipeEnabled: false,
        tabBarScrollEnabled: true,
        tabBarIndicator: () => null,
        tabBarStyle: {
          backgroundColor: "white",
        },
        tabBarItemStyle: {
          width: "auto",
          alignItems: "flex-start",
          backgroundColor: "#5B2FA3",
          marginHorizontal: 5,
          marginVertical: 10,
          borderRadius: 25,
        },
        tabBarLabelStyle: {
          fontSize: 13,
          textTransform: "capitalize",
          fontWeight: "500",
          color: "white"
        },
        tabBarActiveTintColor: "green"
      }}
    >
      <Tab.Screen
        name="Currently Reading"
        component={CurrentlyReadingCarousel}
      />
      <Tab.Screen name="Want To Read" component={Carousel} />
      <Tab.Screen name="Read" component={Carousel} />
      <Tab.Screen name="Did Not Finish" component={Carousel} />
    </Tab.Navigator>
  );
}

As you can see, in the tabBarItemStyle field, I've designed the tabs to look how I want when it is active. But all of the tabs now look like that, rather than only the active one. I tried the tabBarActiveTintColor property, but it doesn't do anything. Is there a way to access some sort of "focused" or "active" field within screenOptions? Or do I have to make a custom tab bar? I just want the backgroundColor property in tabBarItemStyle and the color property in tabBarLabelStyle to change depending on whether or not the tab is active.

1

There are 1 answers

0
Ramin Shahbazi On

The screenOptions can be initialized with a function which receives an object containing both route and navigation and there is a function called isFocused in the navigation object but I don't think it does what you want, you need to make a custom tab bar like the one that the documentation said https://reactnavigation.org/docs/material-top-tab-navigator to achieve that.