YaSh Chaudhary
YaSh Chaudhary

Reputation: 2725

How to add icon in each tab in custom Tabs?

I am using react-navigation .

I want to add icon for the tab.

CustomTabs.js from example directory

Upvotes: 1

Views: 1490

Answers (1)

Caleb Tolu
Caleb Tolu

Reputation: 473

if you are to use react-native-vector-icon is much easier, just create an array like the one i created below, for all the names of the icon you want to use and if you want to use image, then you will have to use image links because the last time i checked react native won't allow you to load static assets dynamically.

Benefit of using an icon especially react-native-vector-icon:

  • Access to tonnes of iconsets.
  • Styling based on if its focused or not.
  • ....and others things i can't remember.

`

        .....
        import Icon from 'react-native-vector-icons/Ionicons';


        const styles = {
                 body: {
                 backgroundColor: '#3b4147',
                 height: 60,
                 },
                 tabWrapper: {
                 flexDirection: 'row',
                 justifyContent: 'center',
                 alignItems: 'center',
                 height: 50,
                 },
                 tabInnerWrapper: {
                 marginRight: 12,
                 marginLeft: 12,
                 justifyContent: 'center',
                 alignItems: 'center',
                 },
                 textStyle: {
                 fontSize: 12,
                 color: '#62666b',
                 },
                 focusTextStyle: {
                 fontSize: 12,
                 color: '#acafb1',
                 },
             };

      const {body, tabWrapper, tabInnerWrapper, textStyle, focusTextStyle} = styles;
      const focusIconColor = '#acafb1';
      const iconColor = '#62666b';

      const IconNames = ['ios-compass-outline', 'ios-cut-outline', 'ios-chatboxes-outline'];
      const IconNamesFocus = ['ios-compass', 'ios-cut', 'ios-chatboxes'];

         const CustomTabBar = ({ navigation: { state, navigate }}) => {
         const { routes } = state;
          return (
          <View style={body}>
            <View style={tabWrapper}>
             {routes && routes.map((route, index) => {
              const focused = index === state.index;
              return (

              <TouchableOpacity
                key={route.key}
                onPress={() => navigate(route.routeName)}
                style={tabInnerWrapper}
              >
                <Icon 
                  name={focused ? IconNamesFocus[index] : IconNames[index]}
                  size={25}
                  color={focused ? focusIconColor : iconColor}
                />

                <Text style={focused ? focusTextStyle : textStyle}>
                  {route.routeName}
                </Text>
              </TouchableOpacity>
            );
          })}

        </View>
      </View>

    );

 };

`

Upvotes: 1

Related Questions