React Native Camera

React Native Camera Kit

We all usually need a camera in our app and Wix has provided a very good library named react-native-camera-kit. Which is very easy to integrate into your app.

In this example, we will make a home screen to open Camera and in the camera, we will have a capture button, a front-to-back camera switch button, a flash setting button, and a cancel button to close the camera. 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.

Installation of Dependency

To use <CameraScreen /> we need to install react-native-camera-kit package. To install this

Open the terminal and jump into your project

cd ProjectName

Run the following command

npm install react-native-camera-kit --save

This command will copy all the dependencies into your node_module directory, You can find the directory in node_module the directory named react-native-camera-kit.

–save is optional, it is just to update the react-native-camera-kit dependency in your package.json file.

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install

Permission to use the Camera for Android

We are using a Native API Camera so we need to add some permission into the AndroidManifest.xml file.

Please add the following permissions in your AndroidMnifest.xml. Go to CameraExample -> android -> app -> main -> AndroidMnifest.xml.

<uses-permission
  android:name="android.permission.CAMERA"
/>
<uses-permission
  android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<uses-permission
  android:name="android.permission.READ_EXTERNAL_STORAGE"
/>
Permission Purpose
CAMERA To access the camera
WRITE_EXTERNAL_STORAGE To store the content in the SD card
READ_EXTERNAL_STORAGE To view the content of the SD card


For more about the permission, you can see this post. Also, you need to do these changes in your project.

Permission to use the Camera for IOS

Please follow the below steps to add the permission in iOS project to use the camera.

Open the project CameraExample -> ios -> ScannerExample.xcworkspace in Xcode.

1. After opening the project in Xcode click on the project from the left sidebar and you will see multiple options in the workspace.

2. Select info tab which is info.plist

3. Click on the plus button to add a permission key “Privacy-Camera Usage Description” and a value which will be visible when permission dialog pops up.

Code to Run Camera in React Native Application

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

App.js

// React Native Camera
// https://aboutreact.com/react-native-camera/

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

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  PermissionsAndroid,
  Alert,
  Platform,
  TouchableHighlight,
} from 'react-native';

// import CameraScreen
import {CameraScreen} from 'react-native-camera-kit';

const App = () => {
  const [isPermitted, setIsPermitted] = useState(false);
  const [captureImages, setCaptureImages] = useState([]);

  const requestCameraPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: 'Camera Permission',
          message: 'App needs camera permission',
        },
      );
      // If CAMERA Permission is granted
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (err) {
      console.warn(err);
      return false;
    }
  };

  const requestExternalWritePermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: 'External Storage Write Permission',
          message: 'App needs write permission',
        },
      );
      // If WRITE_EXTERNAL_STORAGE Permission is granted
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (err) {
      console.warn(err);
      alert('Write permission err', err);
    }
    return false;
  };

  const requestExternalReadPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        {
          title: 'Read Storage Permission',
          message: 'App needs Read Storage Permission',
        },
      );
      // If READ_EXTERNAL_STORAGE Permission is granted
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (err) {
      console.warn(err);
      alert('Read permission err', err);
    }
    return false;
  };

  const openCamera = async () => {
    if (Platform.OS === 'android') {
      if (await requestCameraPermission()) {
        if (await requestExternalWritePermission()) {
          if (await requestExternalReadPermission()) {
            setIsPermitted(true);
          } else alert('READ_EXTERNAL_STORAGE permission denied');
        } else alert('WRITE_EXTERNAL_STORAGE permission denied');
      } else alert('CAMERA permission denied');
    } else {
      setIsPermitted(true);
    }
  };

  const onBottomButtonPressed = (event) => {
    const images = JSON.stringify(event.captureImages);
    if (event.type === 'left') {
      setIsPermitted(false);
    } else if (event.type === 'right') {
      setIsPermitted(false);
      setCaptureImages(images);
    } else {
      Alert.alert(
        event.type,
        images,
        [{text: 'OK', onPress: () => console.log('OK Pressed')}],
        {cancelable: false},
      );
    }
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      {isPermitted ? (
        <View style={{flex: 1}}>
          <CameraScreen
            // Buttons to perform action done and cancel
            actions={{
              rightButtonText: 'Done',
              leftButtonText: 'Cancel'
            }}
            onBottomButtonPressed={
              (event) => onBottomButtonPressed(event)
            }
            flashImages={{
              // Flash button images
              on: require('./assets/flashon.png'),
              off: require('./assets/flashoff.png'),
              auto: require('./assets/flashauto.png'),
            }}
            cameraFlipImage={require('./assets/flip.png')}
            captureButtonImage={require('./assets/capture.png')}
          />
        </View>
      ) : (
        <View style={styles.container}>
          <Text style={styles.titleText}>React Native Camera</Text>
          <Text style={styles.textStyle}>{captureImages}</Text>
          <TouchableHighlight
            onPress={openCamera}
            style={styles.buttonStyle}
          >
            <Text style={styles.buttonTextStyle}>Open Camera</Text>
          </TouchableHighlight>
        </View>
      )}
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    alignItems: 'center',
  },
  titleText: {
    fontSize: 22,
    textAlign: 'center',
    fontWeight: 'bold',
  },
  textStyle: {
    color: 'black',
    fontSize: 16,
    textAlign: 'center',
    padding: 10,
    marginTop: 16,
  },
  buttonStyle: {
    fontSize: 16,
    color: 'white',
    backgroundColor: 'green',
    padding: 5,
    marginTop: 32,
    minWidth: 250,
  },
  buttonTextStyle: {
    padding: 5,
    color: 'white',
    textAlign: 'center',
  },
});

Before running the app you need to make a directory called “assets ” to keep the images that we have used. Download and put all the images in assets as shown

                         

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

Android

      

      

IOS

      

That was the React Native Camera. If you have any doubt 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. 🙂

9 thoughts on “React Native Camera”

  1. i’ve been tried your tutorial about RN Camera, which the icon can small size, i don’t know the size u wear in assets folder.
    and i want to ask you, how can i set the size in this code ?
    im surely want to know how set the size.
    thankyou before 🙂

    Reply
    • Sorry but there is no way to set the size of the icon. You have to manually reduce the size of the icon. I have tried it on the request of 1 AboutReact family member like you but it wasn’t worked.
      I have used 32px*32px icon in the example.

      Reply
  2. * What went wrong:
    A problem occurred evaluating project ‘:app’.
    > Plugin with id ‘kotlin-android’ not found.

    * Try:
    Run with –stacktrace option to get the stack trace. Run with –info or –debug option to get more log output. Run with –scan to get full insights.
    ==============================================================================

    2: Task failed with an exception.
    ———–
    * What went wrong:
    A problem occurred configuring project ‘:app’.
    > compileSdkVersion is not specified. Please add it to build.gradle

    Could You please help me to solve this error

    Reply
  3. Hi, thanks so much for the article. I was wondering if there is a way to simultaneously click a back and front picture, where in the final picture the front camera pic is a small snapshot at the top left side on the screen overlapping the back camera picture.

    Reply

Leave a Comment

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