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

/*This is an Example to make a View Like Android Fragment in React Native*/
import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import FirstScreen from './components/FirstScreen';
import SecondScreen from './components/SecondScreen';
import ThirdScreen from './components/ThirdScreen';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    //state to manage the screen visible at a time
    this.state = { val: 1 };
  }
  renderElement() {
    //You can add N number of Views here in if-else condition
    if (this.state.val === 1) {
      //Return the FirstScreen as a child to set in Parent View
      return <FirstScreen />;
    } else if (this.state.val === 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 />;
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <View style={{ flexDirection: 'row' }}>
          {/*To set the FirstScreen*/}
          <TouchableOpacity
            style={styles.button}
            onPress={() => this.setState({ val: 1 })}>
            <Text style={{ color: '#ffffff' }}>1st View</Text>
          </TouchableOpacity>
          {/*To set the SecondScreen*/}
          <TouchableOpacity
            style={styles.button}
            onPress={() => this.setState({ val: 2 })}>
            <Text style={{ color: '#ffffff' }}>2nd View</Text>
          </TouchableOpacity>
          {/*To set the ThirdScreen*/}
          <TouchableOpacity
            style={styles.button}
            onPress={() => this.setState({ val: 3 })}>
            <Text style={{ color: '#ffffff' }}>3rd View</Text>
          </TouchableOpacity>
        </View>

        {/*Text From Parent Screen*/}
        <Text style={styles.paragraph}>
          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' }}>
          {this.renderElement()}
        </View>
      </View>
    );
  }
}

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

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

FirstScreen.js

import * as React from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';

export default class FirstScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = { valx: 0 };
    // you can define N number of key value paires like JSON.
    this.t = setInterval(() => {
      this.setState({ valx: this.state.valx + 1 });
    }, 1000);
    // Simple interval fundtion which will run in every second.
    // It will increase valx
  }
  componentWillUnmount () {
    clearTimeout(this.t);
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>Content Loaded from First Screen</Text>
        <Text style={styles.paragraph}>{'Timer: ' + this.state.valx}</Text>
        <Image
          style={styles.logo}
          source={{        uri:'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
          }}
        />
      </View>
    );
  }
}

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

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

SecondScreen.js

import * as React from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';

export default class SecondScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = { valx: 0 };
    // you can define N number of key value paires like JSON.
    this.t = setInterval(() => {
      this.setState({ valx: this.state.valx + 1 });
    }, 1000);
    // Simple interval fundtion which will run in every second.
    // It will increase valx
  }
   componentWillUnmount () {
    clearTimeout(this.t);
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>Content Loaded from Second Screen</Text>
        <Text style={styles.paragraph}>{'Timer: ' + this.state.valx}</Text>
        <Image
          style={styles.logo}
          source={{
uri:'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
          }}
        />
      </View>
    );
  }
}

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

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

ThirdScreen.js

import * as React from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';

export default class ThirdScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = { valx: 0 };
    // you can define N number of key value paires like JSON.
    this.t = setInterval(() => {
      this.setState({ valx: this.state.valx + 1 });
    }, 1000);
    // Simple interval fundtion which will run in every second.
    // It will increase valx
  }
  componentWillUnmount () {
    clearTimeout(this.t);
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>Content Loaded from Third Screen</Text>
        <Text style={styles.paragraph}>{'Timer: ' + this.state.valx}</Text>
        <Image
          style={styles.logo}
          source={{
uri:'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
          }}
        />
      </View>
    );
  }
}

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

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
react-native run-ios (macOS only).

Output Screenshots

Android

IOS

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. 🙂

 


Related Posts

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.