How to add buttons on header in React navigation

Introduction :

The header is not only for showing titles. It may also include buttons. Normally, user action related buttons are added to the right of the title, and the back button is added to the left. The button on the left side, i.e. the back button is added automatically if we push one new screen to the navigator. It pushes the screen and adds the button. The default back button is different. It is platform-specific. On iOS, it adds one label that says the previous screen title or says “Back”. But we can customize and override the back press of this button as well.

Example to add one right button :

Let’s learn how we can add one button to the right of the header. To do that, we can pass one function for the headerRight props of Stack.Screen that returns one text or image button. For example :

<Stack.Screen
    name="HomeScreen"
    component={HomeScreen}
    options={{
    headerRight: () => (
        <Button
        onPress={() => alert('Clicked !!')}
        title="menu"
        color="#000"
        />
    ),
    }}
/>

It will give one output like below :

react navigation right button

If you click on this button, it will show one alert. But the problem is that we don’t have access to the HomeScreen state. In most cases, we will require to change the state on a button click.

Changing state on header button click :

To change the state, on the header button click, we can use navigation.setOptions inside a Screen. For example :

import {Text, View, Button} from 'react-native';
import React, { useState } from 'react';

export default function HomeScreen({navigation}) {
  const [message, setMessage] = useState('Default message');

  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => 
      <Button onPress={() => setMessage('Button clicked')} title="change" />
      ,
    });
  }, [navigation, setMessage]);

  return (
    <View
      style={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <View style={{marginTop: 35}}>
        <Text style={{color:'black'}}>{message}</Text>
      </View>
    </View>
  );
}

Here, we have added the button inside the Screen component. It changes the message on click.

If you have only one action to put in the header, you can add that action as a menu button. But, if you have multiple actions, you can’t put them all in the header. For that, you can put one menu button and on click, you can show one popover menu with all other options.

Conclusion :

In this tutorial, we learned how to add one button to the navigation bar in react-navigation. Try to go through the example and drop one comment below if you have any queries.