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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

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

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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, {useState, useEffect} from 'react';

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

const FirstScreen = () => {
  const [value, setValue] = useState(0);

  const interval = setInterval(() => {
    setValue(value + 1);
  }, 1000);

  useEffect(() => {
    return () => {
      console.log('Clear Timeout');
      clearTimeout(interval);
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.paragraphStyle}>
        Content Loaded from First Screen
      </Text>
      <Text style={styles.paragraphStyle}>
        {'Timer: ' + value}
      </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, {useState, useEffect} from 'react';

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

const SecondScreen = () => {
  const [value, setValue] = useState(0);

  const interval = setInterval(() => {
    setValue(value + 1);
  }, 1000);

  useEffect(() => {
    return () => {
      console.log('Clear Timeout');
      clearTimeout(interval);
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.paragraphStyle}>
        Content Loaded from Second Screen
      </Text>
      <Text style={styles.paragraphStyle}>
        {'Timer: ' + value}
      </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, {useState, useEffect} from 'react';

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

const ThirdScreen = () => {
  const [value, setValue] = useState(0);

  const interval = setInterval(() => {
    setValue(value + 1);
  }, 1000);

  useEffect(() => {
    return () => {
      console.log('Clear Timeout');
      clearTimeout(interval);
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.paragraphStyle}>
        Content Loaded from Third Screen
      </Text>
      <Text style={styles.paragraphStyle}>
        {'Timer: ' + value}
      </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

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

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

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.