Example of Grid Image Gallery in React Native

Introduction

Here is an Example of Grid Image Gallery in React Native. We will use FastImage component from react-native-fast-image for our Grid Image Gallery in React Native. If you have no idea about the FastImage then you can get the idea about it from Fast Speed Image Loading using React Native Fast Image.

Image Gallery is the most common thing in an application. To make an Image gallery in React Native we have a number of options available and we are using one of them in this example. You can also see our other Example of Slider Image Gallery in React Native.

FastImage Component

<FastImage
  style={styles.image}
  source={{
    uri: 'https://unsplash.it/400/400?image=1',
    headers: { Authorization: '9876543210' },
  }}
/>

It is very easy to use component. We are going to make a grid of image using Flat list (If you want to get the idea how to do that then you can see Example of GridView using FlatList in React Native) and after clicking on the image from the grid view we are going to open it in modal component for the full view. 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.

Installation of Dependency

To use FastImage component we need to install react-native-fast-image dependency.

To install these dependencies open the terminal and jump into your project using

cd ProjectName

Run the following commands

npm install react-native-fast-image --save

This command will copy all the dependency into your node_module directory.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use

cd ios && pod install && cd ..

Code

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

App.js

/*This is an Example of Grid Image Gallery in React Native*/
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  FlatList,
  Modal,
} from 'react-native';
import FastImage from 'react-native-fast-image';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      imageuri: '',
      ModalVisibleStatus: false,
    };
  }

  ShowModalFunction(visible, imageURL) {
    //handler to handle the click on image of Grid
    //and close button on modal
    this.setState({
      ModalVisibleStatus: visible,
      imageuri: imageURL,
    });
  }

  componentDidMount() {
    var that = this;
    let items = Array.apply(null, Array(120)).map((v, i) => {
      return { id: i, src: 'https://unsplash.it/400/400?image=' + (i + 1) };
    });
    that.setState({
      dataSource: items,
    });
  }

  render() {
    if (this.state.ModalVisibleStatus) {
      return (
        <Modal
          transparent={false}
          animationType={'fade'}
          visible={this.state.ModalVisibleStatus}
          onRequestClose={() => {
            this.ShowModalFunction(!this.state.ModalVisibleStatus, '');
          }}>
          <View style={styles.modelStyle}>
            <FastImage
              style={styles.fullImageStyle}
              source={{ uri: this.state.imageuri }}
              resizeMode={FastImage.resizeMode.contain}
            />
            <TouchableOpacity
              activeOpacity={0.5}
              style={styles.closeButtonStyle}
              onPress={() => {
                this.ShowModalFunction(!this.state.ModalVisibleStatus, '');
              }}>
              <FastImage
                source={{
                  uri:
                    'https://raw.githubusercontent.com/AboutReact/sampleresource/master/close.png',
                }}
                style={{ width: 35, height: 35, marginTop: 16 }}
              />
            </TouchableOpacity>
          </View>
        </Modal>
      );
    } else {
      return (
        <View style={styles.container}>
          <Text
            style={{
              padding: 16,
              fontSize: 20,
              color: 'white',
              backgroundColor: 'green',
            }}>
            Image Gallery
          </Text>
          <FlatList
            data={this.state.dataSource}
            renderItem={({ item }) => (
              <View style={{ flex: 1, flexDirection: 'column', margin: 1 }}>
                <TouchableOpacity
                  key={item.id}
                  style={{ flex: 1 }}
                  onPress={() => {
                    this.ShowModalFunction(true, item.src);
                  }}>
                  <FastImage
                    style={styles.image}
                    source={{
                      uri: item.src,
                    }}
                  />
                </TouchableOpacity>
              </View>
            )}
            //Setting the number of column
            numColumns={3}
            keyExtractor={(item, index) => index.toString()}
          />
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 30,
  },
  image: {
    height: 120,
    width: '100%',
  },
  fullImageStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    height: '100%',
    width: '98%',
    resizeMode: 'contain',
  },
  modelStyle: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.4)',
  },
  closeButtonStyle: {
    width: 25,
    height: 25,
    top: 9,
    right: 9,
    position: 'absolute',
  },
});

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

This is how you can make Grid Image Gallery in React Native. 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

6 thoughts on “Example of Grid Image Gallery in React Native”

  1. I want to build something similar but, instead of images, each square should contain another react component. Coincidentally, part of the component I want to display is an image but also there is text information so, ideally, just a responsive grid of components. Any suggestions on ideas of how to start?

    Reply

Leave a Comment

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