How to Add Icon in Tab Navigation in React Native

In the world of mobile app development, creating an intuitive and engaging user interface is key to enhancing user experience. React Native, a popular framework for building mobile applications, offers a variety of features to achieve this, including tab navigation. Tab navigation allows users to switch between different views or functionalities of an app quickly. Adding icons to this navigation further enhances usability by providing visual cues that guide users, saving space, and maintaining brand consistency. In this blog post, we’ll walk you through a step-by-step tutorial on how to add icons to tab navigation in React Native.

Tab Navigation

Tab navigation in React Native is a method that allows users to navigate through different screens of an app by tapping on tabs, usually displayed at the top or bottom of the screen. This feature is implemented using the react-navigation library, which supports various navigation patterns, including stack navigation, drawer navigation, and of course, tab navigation.

Importance of Icons

The integration of icons within tab navigation plays a pivotal role in elevating the user interface. Icons serve as potent visual symbols, offering several key advantages:

  • Visual Cues: Icons provide immediate visual cues that succinctly convey the purpose of each tab. This visual representation allows users to navigate the app more intuitively, bypassing the need for textual interpretation and thus speeding up the navigation process.
  • Space Efficiency: On mobile platforms, where screen real estate is at a premium, icons offer a space-efficient means of communication. By replacing or supplementing text labels with icons, developers can make optimal use of the limited screen space, ensuring a clutter-free and aesthetically pleasing interface.
  • Brand Consistency: Consistent use of iconography across an app can significantly bolster brand identity. Custom icons that align with the brand’s visual language can enhance recognition and contribute to a cohesive user experience.

Project Setup

First, let’s set up a basic React Native project. If you haven’t already, initialize a new project by running:

npx react-native init MyTabApp

Next, install the necessary dependencies for navigation and icons:

npm install @react-navigation/native @react-navigation/bottom-tabs react-native-gesture-handler react-native-reanimated react-native-screens react-native-vector-icons

Installing Icon Library

For this tutorial, we’ll use react-native-vector-icons, a popular library that offers a wide range of icon sets.

To install, run:

npm install react-native-vector-icons

After installation, link the library to your project (if required for your version of React Native) and choose from various icon sets like FontAwesome, MaterialIcons, and others.

Creating Tab Navigator

Import createBottomTabNavigator from @react-navigation/bottom-tabs and define your screens:

import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';

const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

Adding Icons

To add icons to your tabs, use the tabBarIcon property in the screen options. Import your desired icon set from react-native-vector-icons and configure like so:

import MaterialIcons from 'react-native-vector-icons/MaterialIcons';

<Tab.Screen
  name="Home"
  component={HomeScreen}
  options={{
    tabBarIcon: ({color, size}) => (
      <MaterialIcons name="home" color={color} size={size} />
    ),
  }}
/>

Customize the icon size and color to fit your app’s design.

You’ll need to modify your App.js or create a new file if you prefer organizing your navigation separately.

Here’s the Whole Updated Code:

import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import {View, Text} from 'react-native';

// Define your screens
function HomeScreen() {
  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <Text>Home Screen</Text>
    </View>
  );
}

function SettingsScreen() {
  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <Text>Settings Screen</Text>
    </View>
  );
}

// Create the bottom tab navigator
const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator
      screenOptions={({route}) => ({
        tabBarIcon: ({focused, color, size}) => {
          let iconName;

          if (route.name === 'Home') {
            iconName = focused ? 'home' : 'home-outline';
          } else if (route.name === 'Settings') {
            iconName = focused ? 'settings' : 'settings-outline';
          }

          // Return any component that you like here!
          return <MaterialIcons name={iconName} size={size} color={color} />;
        },
        tabBarActiveTintColor: 'tomato',
        tabBarInactiveTintColor: 'gray',
      })}
    >
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

// Wrap the tab navigator in a navigation container
export default function App() {
  return (
    <NavigationContainer>
      <MyTabs />
    </NavigationContainer>
  );
}

This code sets up a basic app with bottom tab navigation. The tabBarIcon property dynamically assigns icons to each tab, changing based on whether the tab is focused. We use the MaterialIcons component from react-native-vector-icons to render the icons, specifying the icon name, size, and color.

Note:

  • You might need to link the react-native-vector-icons library manually in some cases, depending on your React Native version and setup.
  • Ensure you have the correct icon names. In this example, we used placeholder names like ‘home’ and ‘settings’. You can find the exact names in the react-native-vector-icons directory or on their GitHub repository.

Custom Icons

Using Images

For custom icons in bitmap format (e.g., PNG, JPEG):

  1. Place your icon images in an assets/images folder.
  2. Import and use your icons:
import React from 'react';
import { Image } from 'react-native';

const HomeIcon = require('./assets/images/home.png');

const MyHomeIcon = ({ size, color }) => (
  <Image source={HomeIcon} style={{ width: size, height: size, tintColor: color }} />
);

<Tab.Screen
  name="Home"
  component={HomeScreen}
  options={{
    tabBarIcon: ({ color, size }) => <MyHomeIcon size={size} color={color} />,
  }}
/>

Using SVGs

For SVG icons, use react-native-svg:

npm install react-native-svg

Convert SVG to a React component and use it:

import React from 'react';
import Svg, { Path } from 'react-native-svg';

const MyCustomIcon = ({ size, color }) => (
  <Svg width={size} height={size} viewBox="0 0 24 24">
    <Path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 14l-5-5h4V7h2v5h4l-5 5z" fill={color} />
  </Svg>
);

<Tab.Screen
  name="Home"
  component={HomeScreen}
  options={{
    tabBarIcon: ({ color, size }) => <MyCustomIcon size={size} color={color} />,
  }}
/>

Animated Icons

Animating icons adds a dynamic touch to your app. Use React Native’s Animated API:

import React, { useState } from 'react';
import { Animated } from 'react-native';

const AnimatedIcon = ({ name, size, color }) => {
  const [animation] = useState(new Animated.Value(1));

  const handlePressIn = () => {
    Animated.spring(animation, { toValue: 1.5, useNativeDriver: true }).start();
  };

  const handlePressOut = () => {
    Animated.spring(animation, { toValue: 1, useNativeDriver: true }).start();
  };

  const animatedStyle = { transform: [{ scale: animation }] };

  return (
    <Animated.View style={animatedStyle} onPressIn={handlePressIn} onPressOut={handlePressOut}>
      <MaterialIcons name={name} size={size} color={color} />
    </Animated.View>
  );
};

Best Practices

Icon Choice

  • Clarity and Intuition: Choose icons that are easily recognizable and convey their function clearly. Test with users if possible to ensure your icons make sense to others.

Accessibility

  • Labels: Use the accessibilityLabel prop on your icons to provide screen readers with a description of the icon’s action or purpose. This ensures that all users, regardless of their abilities, can navigate your app effectively.

Performance

  • Optimize Usage: While custom and animated icons can enhance your app, they can also impact performance, especially if overused or not optimized. For bitmap images, use the appropriate size and resolution to avoid unnecessary scaling. For SVGs and animations, keep the complexity in check to avoid rendering issues.

Conclusion

Adding icons to tab navigation in React Native can significantly improve user experience by making your app more intuitive and visually appealing. By following the steps outlined in this tutorial, you’ll be able to enhance your app’s navigation with icons, contributing to a polished and user-friendly interface

Additional Resources

Leave a Comment