How to Make a View Like Android Fragment in React Native

React Native Android Fragment View

In this post, you will see How to Make a View Like Android Fragment in React Native. Developers from android development backgrounds know very well about the Fragment in Android but for those who haven’t heard about that

Android Fragment is the part of the activity, it is also known as sub-activity. There can be more than one fragment in an activity. Fragments represent multiple screens inside one activity.

There is nothing like a Fragment Component in React Native to make a view like the Android Fragment for Android and IOS. To make the fragmented view we have to manage the visibility of the child view using state. In this example, I have made a state to store a number. This number will be used to return the screen we want to show using a function. 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.

Project Structure

To start with this example you need to create a directory named components in your project and create three files FirstScreen.js, SecondScreen.js, and ThirdScreen.js in it.

Code

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

App.js

// How to Make a View Like Android Fragment in React Native
// https://aboutreact.com/android-fragment-view/

// import React in our code
import React, {useState} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  Text,
  View,
  StyleSheet,
  TouchableOpacity,
  LogBox,
} from 'react-native';

import FirstScreen from './components/FirstScreen';
import SecondScreen from './components/SecondScreen';
import ThirdScreen from './components/ThirdScreen';

LogBox.ignoreAllLogs(); //Ignore all log notifications

const App = () => {
  const [index, setIndex] = useState(1);

  const RenderElement = () => {
    //You can add N number of Views here in if-else condition
    if (index === 1) {
      //Return the FirstScreen as a child to set in Parent View
      return <FirstScreen />;
    } else if (index === 2) {
      //Return the SecondScreen as a child to set in Parent View
      return <SecondScreen />;
    } else {
      //Return the ThirdScreen as a child to set in Parent View
      return <ThirdScreen />;
    }
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <View style={{flexDirection: 'row'}}>
          {/*To set the FirstScreen*/}
          <TouchableOpacity
            style={styles.buttonStyle}
            onPress={() => setIndex(1)}>
            <Text style={{color: '#ffffff'}}>1st View</Text>
          </TouchableOpacity>
          {/*To set the SecondScreen*/}
          <TouchableOpacity
            style={styles.buttonStyle}
            onPress={() => setIndex(2)}>
            <Text style={{color: '#ffffff'}}>2nd View</Text>
          </TouchableOpacity>
          {/*To set the ThirdScreen*/}
          <TouchableOpacity
            style={styles.buttonStyle}
            onPress={() => setIndex(3)}>
            <Text style={{color: '#ffffff'}}>3rd View</Text>
          </TouchableOpacity>
        </View>

        {/*Text From Parent Screen*/}
        <Text style={styles.paragraphStyle}>
          Example of view like fragment in React Native
        </Text>

        {/*View to hold the child screens 
        which can be changed on the click of a button*/}
        <View style={{backgroundColor: '#ffffff'}}>
          <RenderElement />
        </View>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraphStyle: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  buttonStyle: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#808080',
    padding: 10,
    margin: 2,
  },
});

export default App;

Open components/FirstScreen.js in any code editor and replace the code with the following code.

FirstScreen.js

// How to Make a View Like Android Fragment in React Native
// https://aboutreact.com/android-fragment-view/

// import React in our code
import React from 'react';

// import all the components we are going to use
import {Text, View, StyleSheet, Image} from 'react-native';

const FirstScreen = () => {

  return (
    <View style={styles.container}>
      <Text style={styles.paragraphStyle}>
        Content Loaded from First Screen
      </Text>
      <Image
        style={styles.logoStyle}
        source={{
          uri:
            'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 24,
  },
  paragraphStyle: {
    margin: 24,
    marginTop: 0,
    fontSize: 14,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  logoStyle: {
    height: 50,
    width: 50,
  },
});

export default FirstScreen;

Open components/SecondScreen.js in any code editor and replace the code with the following code.

SecondScreen.js

// How to Make a View Like Android Fragment in React Native
// https://aboutreact.com/android-fragment-view/

// import React in our code
import React from 'react';

// import all the components we are going to use
import {Text, View, StyleSheet, Image} from 'react-native';

const SecondScreen = () => {

  return (
    <View style={styles.container}>
      <Text style={styles.paragraphStyle}>
        Content Loaded from Second Screen
      </Text>
      <Image
        style={styles.logoStyle}
        source={{
          uri:
            'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 24,
  },
  paragraphStyle: {
    margin: 24,
    marginTop: 0,
    fontSize: 14,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  logoStyle: {
    height: 50,
    width: 50,
  },
});

export default SecondScreen;

Open components/ThirdScreen.js in any code editor and replace the code with the following code.

ThirdScreen.js

// How to Make a View Like Android Fragment in React Native
// https://aboutreact.com/android-fragment-view/

// import React in our code
import React from 'react';

// import all the components we are going to use
import {Text, View, StyleSheet, Image} from 'react-native';

const ThirdScreen = () => {

  return (
    <View style={styles.container}>
      <Text style={styles.paragraphStyle}>
        Content Loaded from Third Screen
      </Text>
      <Image
        style={styles.logoStyle}
        source={{
          uri:
            'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 24,
  },
  paragraphStyle: {
    margin: 24,
    marginTop: 0,
    fontSize: 14,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  logoStyle: {
    height: 50,
    width: 50,
  },
});

export default ThirdScreen;

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 to make a view like Android Fragment in React Native for Android and iOS. 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. 🙂

2 thoughts on “How to Make a View Like Android Fragment in React Native”

  1. hello

    I want to add my page the fragment just like yours please I try in three days I didn’t
    for navigation for three other pages we create outside of principle page

    Reply

Leave a Comment

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