3 Ways to Add Image Icon Inside Navigation Bar in React Native

3 Ways to Add Image Icon Inside Navigation Bar

In this example, we will see 3 Ways to Add Image Icon Inside Navigation Bar in React Native. If you have worked with React Navigation then you probably know what is Navigation Bar, many people also know it as an Action Bar.

Adding anything inside a navigation bar is very easy in React Navigation. React Navigation provides so many props to customise the navigation bar of your application, you just have to create your custom component and pass it to the props provided.

To add any Image/button or another component in navigation bar we can use headerLeft to add anything on the left side or headerRight to add anything on right.

Options to Add Image Icon Inside Navigation Bar

Majorly there are 2 ways to set your component/Image/Button in navigation bar, either for all the screens or for a specific screen but there are further 2 ways to set component/Image/Button in navigation bar so here we are listing mentioning 3 ways (2 for specific screen and 1 for all)

1. To set any Component/Image/Button for all the screen you can use screenOptions while creating Navigator Stack. Stack.Navigator is the parent component of all the Stack.Screen so once you set component here it will be reflected in all the screens under it.

<Stack.Navigator
  initialRouteName="HomeActivity"
  screenOptions={{headerLeft: () => <ActionBarImage />}}>
  <Stack.Screen>
    .....
  </Stack.Screen>
</Stack.Navigator>

2. To set any Component/Image/Button in the navigation bar for a particular screen, you can use options while creating Navigator Stack. Stack.Screen provides this option to set for the specific screen.

<Stack.Screen
  name="HomeActivity"
  component={HomeActivity}
  options={{
    title: 'Home', //Set Header Title
    headerStyle: {
      backgroundColor: '#d8d8d8', //Set Header color
    },
    headerTintColor: 'black', //Set Header text color
    headerTitleStyle: {
      fontWeight: 'bold', //Set Header text style
    },
    headerLeft: () => <ActionBarImage />,
  }}
/>

3. Here is the other way to set any Component/Image/Button in the navigation bar for a particular screen. If you don’t want to touch your Navigator Stack then you can do it using useLayoutEffect() hook provided by React.

const HomeActivity = ({navigation}) => {
  React.useLayoutEffect(() => {
    navigation.setOptions({
        headerLeft: () => <ActionBarImage />,
    });
  }, [navigation]);
  return (
    ..........
  );
}

In this example, We will create an ActionBarImage component which can be set easily from anywhere if we follow any option from above. We will set Image/Icon on the left side with header title, header background, and text color of the title. So let’s get started.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

For navigation we need to add react-navigation and other supporting dependencies.

To install the dependencies open the terminal and jump into your project

cd ProjectName

1. Install react-navigation

npm install @react-navigation/native --save

2. Other supporting libraries react-native-screens and react-native-safe-area-context

npm install react-native-screens react-native-safe-area-context --save

react-native-screens package requires one additional configuration step to properly work on Android devices. Edit MainActivity.java file which is located in android/app/src/main/java/<your package name>/MainActivity.java.

Add the following code to the body of MainActivity class:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(null);
}

and make sure to add the following import statement at the top of this file below your package statement:

import android.os.Bundle;

This change is required to avoid crashes related to View state being not persisted consistently across Activity restarts.

3. For the Stack Navigator install

npm install @react-navigation/native-stack --save

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install

Project File Structure

To start with this example you need to create a directory named pages in your project and create two files HomeActivity.js and ActionBarImage.js in it.

Code

Now open App.js in any code editor and replace the code with the following code

App.js

// 3 Ways to Add Image Icon Inside Navigation Bar in React Native
// https://aboutreact.com/react-native-image-icon-inside-navigation-bar/

import React from 'react';

import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';

import HomeActivity from './pages/HomeActivity';
import ActionBarImage from './pages/ActionBarImage';

const Stack = createNativeStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="HomeActivity"
        //screenOptions={{headerLeft: () => <ActionBarImage />}}
      >
        <Stack.Screen
          name="HomeActivity"
          component={HomeActivity}
          options={{
            title: 'Home', //Set Header Title
            headerStyle: {
              backgroundColor: '#d8d8d8', //Set Header color
            },
            headerTintColor: 'black', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
            // headerLeft: () => <ActionBarImage />,
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

Open pages/HomeActivity.js in any code editor and replace the code with the following code.

HomeActivity.js

// 3 Ways to Add Image Icon Inside Navigation Bar in React Native
// https://aboutreact.com/react-native-image-icon-inside-navigation-bar/

import React from 'react';
import {SafeAreaView, Text} from 'react-native';
import ActionBarImage from './ActionBarImage';

const HomeActivity = ({navigation}) => {
  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerLeft: () => <ActionBarImage />,
    });
  }, [navigation]);

  return (
    <SafeAreaView style={{flex: 1}}>
      <Text
        style={{
          fontSize: 25,
          textAlign: 'center',
          marginVertical: 10,
        }}>
        3 Ways to Add Image Icon Inside Navigation Bar
        in React Native
      </Text>
      <Text style={{textAlign: 'center', color: 'grey'}}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

export default HomeActivity;

Open pages/ActionBarImage.js in any code editor and replace the code with the following code.

ActionBarImage.js

// 3 Ways to Add Image Icon Inside Navigation Bar in React Native
// https://aboutreact.com/react-native-image-icon-inside-navigation-bar/

import React from 'react';

import {View, Image} from 'react-native';

const ActionBarImage = () => {
  return (
    <View style={{flexDirection: 'row'}}>
      <Image
        source={{
          uri:
            'https://raw.githubusercontent.com/AboutReact/sampleresource/master/logosmalltransparen.png',
        }}
        style={{
          width: 40,
          height: 40,
          borderRadius: 40 / 2,
          marginLeft: 15,
        }}
      />
    </View>
  );
};

export default ActionBarImage;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

Output in Online Emulator

This is how you can set Image Icon inside Navigation Bar. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

3 thoughts on “3 Ways to Add Image Icon Inside Navigation Bar in React Native”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.