Image Mapper in React Native to Create Clickable Areas on Image

React Native Image Mapper

In this post, we will see Image Mapper in React Native. With the help of Image Mapper, you can create clickable areas on an image. A simple example of Image Mapper is, if you have an image that shows the hierarchy of any organization and you want any user to redirect to the details related to the hierarchy item then you can use the Image mapper to create that area clickable and on click of that area, you can redirect the user to anywhere you want.

You can see HTML Image Maps for a better understanding.

Image Mapper in React Native Example Overview

In this example, we will use the ImageMapper component in place of the Image component to load the image. This ImageMapper component has an imgMap prop which provides us an option to pass the maps. When we pass the maps in the component it loads the image with the mapper. To handle any click on the mapped area, we have created mapperAreaClickHandler and passed it in onPress prop.

You can search for “image map generator” on google to create image maps

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.

Installation of Dependency

To use ImageMapper component we need to install react-native-image-mapper dependency and to install that jump into your project using

cd ProjectName

Run the following commands

npm install react-native-image-mapper --save

Code

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

App.js

// Image Mapper in React Native to Create Clickable Areas on Image
// https://aboutreact.com/react-native-image-mapper/

// Import React
import React, { useState } from 'react';
// Import Required Components
import { View, Text } from 'react-native';

//Import ImageMapper Component
import ImageMapper from 'react-native-image-mapper';

const getRandomColor = () => {
  //Function to return random color
  //To highlight the mapping area
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (var i = 0; i < 6; i++)
    color += letters[Math.floor(Math.random() * 16)];
  return color;
};

const App = () => {
  //State for the selected area
  const [selectedAreaId, setSelectedAreaId] = useState([]);

  const mapperAreaClickHandler = async (item, idx, event) => {
    const currentSelectedAreaId = selectedAreaId;
    if (Array.isArray(currentSelectedAreaId)) {
      const indexInState = currentSelectedAreaId.indexOf(item.id);
      if (indexInState !== -1) {
        console.log('Removing id', item.id);
        setSelectedAreaId([
          ...currentSelectedAreaId.slice(0, indexInState),
          ...currentSelectedAreaId.slice(indexInState + 1),
        ]);
      } else {
        alert(`Clicked Item Id: ${item.id}`);
        console.log('Setting Id', item.id);
        setSelectedAreaId([...currentSelectedAreaId, item.id]);
      }
    } else {
      if (item.id === currentSelectedAreaId) {
        setSelectedAreaId(null);
      } else {
        setSelectedAreaId(item.id);
      }
    }
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', padding: 30 }}>
      <Text
        style={{
          fontSize: 30,
          textAlign: 'center',
          marginTop: 40
        }}>
        Image Mapper Example in React Native
      </Text>
      <Text
          style={{
            fontSize: 25,
            marginTop: 20,
            marginBottom: 30,
            textAlign: 'center',
          }}>
          www.aboutreact.com
        </Text>
      <ImageMapper
        imgHeight={551}
        imgWidth={244}
        imgSource={{
          uri:
            'https://raw.githubusercontent.com/msalo3/react-native-image-mapper/master/Examples/human.png',
        }}
        imgMap={RECTANGLE_MAP}
        onPress={
          (item, idx, event) => 
            mapperAreaClickHandler(item, idx, event)
        }
        containerStyle={{ top: 10 }}
        selectedAreaId={selectedAreaId}
        multiselect
      />
    </View>
  );

};

export default App;

// Maps to Create Clickable Areas
const RECTANGLE_MAP = [
  {
    id: '0',
    name: 'Left Foot',
    shape: 'rectangle',
    x2: 110,
    y2: 540,
    x1: 80,
    y1: 500,
    prefill: getRandomColor(),
    fill: 'blue',
  },
  {
    id: '1',
    name: 'Right Foot',
    shape: 'rectangle',
    x2: 155,
    y2: 540,
    x1: 125,
    y1: 500,
    prefill: getRandomColor(),
    fill: 'blue',
  },
  {
    id: '2',
    name: 'Left Knee',
    shape: 'rectangle',
    x2: 110,
    y2: 400,
    x1: 80,
    y1: 370,
    prefill: getRandomColor(),
    fill: 'blue',
  },
  {
    id: '3',
    name: 'Right Knee',
    shape: 'rectangle',
    x2: 155,
    y2: 400,
    x1: 125,
    y1: 370,
    prefill: getRandomColor(),
    fill: 'blue',
  },
  {
    id: '4',
    name: 'Stomach',
    shape: 'rectangle',
    x2: 155,
    y2: 240,
    x1: 80,
    y1: 165,
    prefill: getRandomColor(),
    fill: 'blue',
  },
  {
    id: '5',
    name: 'Left Hand',
    shape: 'rectangle',
    x2: 40,
    y2: 315,
    x1: 5,
    y1: 250,
    prefill: getRandomColor(),
    fill: 'blue',
  },
  {
    id: '6',
    name: 'Right Hand',
    shape: 'rectangle',
    x2: 235,
    y2: 315,
    x1: 200,
    y1: 250,
    prefill: getRandomColor(),
    fill: 'blue',
  },
  {
    id: '7',
    name: 'Face',
    shape: 'rectangle',
    x2: 145,
    y2: 70,
    x1: 90,
    y1: 30,
    prefill: getRandomColor(),
    fill: 'blue',
  },
  {
    id: '8',
    name: 'Head',
    shape: 'rectangle',
    x2: 145,
    y2: 30,
    x1: 90,
    y1: 0,
    prefill: getRandomColor(),
    fill: 'blue',
  },
];

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

Image Mapper Example Screenshot 1    Image Mapper Example Screenshot 2

That was Image Mapper in React Native to Create Clickable Areas on Images. If you have any doubts or 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 “Image Mapper in React Native to Create Clickable Areas on Image”

Leave a Comment

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