React Native navigation bar and button

Here we will be focusing on header navigation. We will add buttons to the header, which is the best way to interact with a header. We have already learned about bottom tabs. Let's create buttons in the header, and then we will understand the code part by part.

Create two files named first.js and second .js

First.js code:

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
 
const First = ({navigation}) => {
  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerTitle: (props) => (
        <Text
          {...props}
          style={{color: 'black', fontWeight: 'bold',fontSize:26}}>
         tutorials and examples
        </Text>
      ),
      headerStyle: {
        backgroundColor: '#b3ffff'
      },
    });
  }, [navigation]);
 
  return (
    <SafeAreaView style={{flex: 1, backgroundColor: '#e6ffff'}}>
      <View style={styles.container}>
        <Text style={styles.header}>
          this is first page
        </Text>
        <Text>Welcome :)</Text>
 
        <TouchableOpacity
          onPress={() => navigation.navigate('Second')}
          style={styles.button_Style}>
          <Text style={styles.text_Style}>
            Click to see Left and Right align header
          </Text>
        </TouchableOpacity>
      </View>
     
    </SafeAreaView>
  );
};
 
export default First;
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding:30,
  },
  button_Style: {


    height: 40,
    padding: 10,
    backgroundColor: '#b3ffff',
    borderRadius: 2,
    marginTop: 12,
  },
  header: {
    fontSize: 30,
    textAlign: 'center',
    fontWeight:'bold',
    marginVertical: 200,
  },
  text_Style: {
    color: 'black',
 
  },
});

Second.js code:

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
   Text,
  TouchableOpacity,
  View,
} from 'react-native';
 
const Second = ({navigation}) => {
  React.useLayoutEffect(() => {
    navigation.setOptions({
      title: 'Second Page', 
      headerStyle: {
        backgroundColor: '#99ffcc',
      },
      headerTitleStyle: {
        fontWeight: 'bold',
        fontSize:20,
        padding:15
      },
      headerLeft: () => (
        <TouchableOpacity
          onPress={() => alert('hello from left menu')}
          style={{marginLeft: 10}}>
          <Text style={{color: 'black'}}>Left Menu</Text>
        </TouchableOpacity>
      ),
      headerRight: () => (
        <TouchableOpacity
          onPress={() => alert('hello from Right Menu ')}
          style={{marginRight: 25}}>
          <Text style={{color: 'black'}}>Right Menu</Text>
        </TouchableOpacity>
      ),
    });
  }, [navigation]);
 
  return (
    <SafeAreaView style={{flex: 1, backgroundColor: '#ccffe6'}}>
      <View style={styles.container}>
        <Text style={styles.header}>
         welcome :) you can see right and left option here
        </Text>
      </View>
    </SafeAreaView>
  );
};
 
export default Second;
 
const styles = StyleSheet.create({
  container: {
     padding: 20,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
   
  },
  header: {
    fontSize: 25,
    marginVertical: 25,
    textAlign: 'center',
  },
  text_Style: {
    color: '#fff',
    textAlign: 'center',
  },
});

App.js code :

import 'react-native-gesture-handler';
import {NavigationContainer} from '@react-navigation/native';
import React from 'react';
 import {createStackNavigator} from '@react-navigation/stack';
 
import First from './first';
import Second from './second';
 
const Stack = createStackNavigator();
 
const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="FirstPage">
        <Stack.Screen name="FirstPage" component={First} />
        <Stack.Screen name="SecondPage" component={Second} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};
 export default App;

Output:

React native navigation bar and button
React native navigation bar and button

After clicking on the button on the first page, you will be directed to the second page.

React native navigation bar and button
React native navigation bar and button

After clicking on the left menu, you will get an alert "hello from the left menu," After clicking on the right menu, you will get an alert as "hello from the left menu".

So this was about the creation of a responsive and customized header. Let us discuss some important parts of the code.

Explanation of First page code :

headerTitle: (props) => (
        <Text
          {...props}
          style={{color: 'black', fontWeight: 'bold',fontSize:26}}>
         tutorials and examples
        </Text>
      ),

 In this part of code we have declared header and given it name “tutorials and example” and styled it.

<TouchableOpacity
          onPress={() => navigation.navigate('Second')}
          style={styles.button_Style}>
          <Text style={styles.text_Style}>
            Click to see Left and Right align header
          </Text>
        </TouchableOpacity>

This part is responsible for the button and connection to the second page.

We have made a button, and we know that the onPress prop decides what will happen after clicking the button. So here we have declared if the user presses the button, then the user will be directed to the second page. You can navigate wherever you want. Just make sure to follow proper syntax and structure.

Second page code explanation :

You must have got some ideas about the basic header from the previous explanation. This file contains the right header and left header, so that we will talk about them.

headerLeft: () => (
        <TouchableOpacity
          onPress={() => alert('hello from left menu')}
          style={{marginLeft: 10}}>
          <Text style={{color: 'black'}}>Left Menu</Text>
        </TouchableOpacity>
      ),

This is the left header. We have declared it as a button, and an alert will be given after pressing it. So whatever you want to add to the left header, you have to write it into headerLeft.

headerRight: () => (
        <TouchableOpacity
          onPress={() => alert('hello from Right Menu ')}
          style={{marginRight: 25}}>
          <Text style={{color: 'black'}}>Right Menu</Text>
        </TouchableOpacity>
      ),

The same thing has been done to the right header. If you have understood the working of the left header, then understanding the working of the right header is simple as the code is identical. The only difference is the availability and name of it on display.

App.js code  :

import First from './first';
import Second from './second';
 We have imported components from first.js and second.js file .
<NavigationContainer>
      <Stack.Navigator initialRouteName="FirstPage">
        <Stack.Screen name="FirstPage" component={First} />
        <Stack.Screen name="SecondPage" component={Second} />
      </Stack.Navigator>
    </NavigationContainer>

We have already discussed the working of the First Page and Second Page. In App.js code we are using stack navigator. If you have read stack navigator documentation, then understanding this code is simple if not, then please go through the documentation of stack navigation. Two stack screens are defined here and they are taking components of the First Page and Second Page and they are rendered in the output.


Related Topics

React Native Status Bar

What is the status bar? The simplest and easiest answer to this question can be answered by looking at your mobile phone's top section. What can you see? Most probably, it's...

4 minutes read.

React Native Sound

It is a great way to connect to the user. Just a tiny "ting" of any email received, or some sound for deleting a file or sound for sending a...

8 minutes read.

Basic knowledge of firebase for React Native

Firebase for react-native : Firebase is a mobile and web application development platform which is created in 2014 by google. It is a product of google which is offered to developers...

7 minutes read.

React Native Animations

Animation: animation is a method in which puppets, figures, drawings, etc., appear as moving creatures, making an illusion that things are moving. It is a unique way of expressing something...

6 minutes read.

Lifecycle of React Native Components

We are familiar with the word “lifecycle”. In human life, the lifecycle has three phases - birthlifedeath In react native its component lifecycle is almost the same as the human lifecycle. The...

6 minutes read.

TouchableOpacity in React Native

Touchable opacity is the most suited example if you want to make views respond to proper touch. If you want to control the opacity then it can be done by...

3 minutes read.

React Native API

API API stands for an Application programming interface. API allows communication between two software and is also responsible for data sharing. It takes the asked data from the server and delivers...

6 minutes read.

React Native Components

React Native components are the same as ordinary react components, but they are different in terms of rendering and styling. All react code lives in react components. They are independent...

16 minutes read.

HTTP in React Native

Networking HTTP in React-native: we all are aware that react native is a javascript framework.HTTP is nothing but an API request, and you might think that what is the need for an...

4 minutes read.

Why to Learn React Native

The demand for smartphone applications is ever-changing. The elder ones disappear from our remembrances, and smartphones and new applications come each day. In this turbulent ecosystem, it is struggling for...

4 minutes read.

What is a Bridge in React Native?

A React Native is generally composed of two fields or two parts: The first part is the code of JavaScript.The second one is native code. The ability to build a bridge between...

3 minutes read.

React Native navigation bar and button

Here we will be focusing on header navigation. We will add buttons to the header, which is the best way to interact with a header. We have already learned about...

4 minutes read.

React native calender

In this article, we will be learning to add calendar features to react native app. So before creating the calendar, we do need to install a few packages or add some...

3 minutes read.

React Native indicator

React native activity indicator : React native activity indicator is one of the react-native components. We all have seen it several times. It's the loader. Look at the picture below - So now...

4 minutes read.

React Native Creating Components

React elements are where all React codes reside. The React elements are very similar to the regular React components, which have a unique style and offer contrast. Working with views When you...

3 minutes read.

TouchableHighlight in React Native

It is just a wrapper for making touch work properly, and it is the conventional way of handling touch gestures. Today's most future-proof solution is pressable API. pressable manages all...

2 minutes read.

React Native Pressable

It manages all the touch inputs, and it is one of the core wrappers introduced in July 2022. The Two important features of pressable are listed below- onPressInonPressOut onpressIn: We already know the...

3 minutes read.

React Native Fonts

The font is one of the important essences of any good UI(User Interface). It is very important to have a clear and beautiful font in your app. In this module,...

4 minutes read.

React Native Tutorial

Introduction to react native : React-native is an open-source javascript framework that can be used to develop native mobile apps for IOS and android. It is released by Facebook in 2015...

4 minutes read.

Advantages and Disadvantages of React Native

Advantages of using React Native It is observed that React Native stands out from most of the existing methods of cross-platform application development, like Ionic or Cordova, because React Native renders...

3 minutes read.