android – How to access the camera – React Native-ThrowExceptions

Exception or error:

This should be included in the react-native APIs but I cannot seem to find any API included out of the box.

I want to open up the camera on the click of a button. I can see some APIs just for iOS but react-native should make things cross-platform.

Does anyone know how to access the camera (not the gallery) using react-native?

How to solve:

You might like to use react-native-camera module for this.

Here’s an example usage of the library:

'use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  Dimensions,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from 'react-native';
import Camera from 'react-native-camera';

class BadInstagramCloneApp extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Camera
          ref={(cam) => {
            this.camera = cam;
          }}
          style={styles.preview}
          aspect={Camera.constants.Aspect.fill}>
          <Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
        </Camera>
      </View>
    );
  }

  takePicture() {
    const options = {};
    //options.location = ...
    this.camera.capture({metadata: options})
      .then((data) => console.log(data))
      .catch(err => console.error(err));
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  capture: {
    flex: 0,
    backgroundColor: '#fff',
    borderRadius: 5,
    color: '#000',
    padding: 10,
    margin: 40
  }
});

AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);

###

In React Native you can access the camera by first installing it using NPM:
npm install react-native-camera –save
react-native link react-native-camera

Then use this in your Component:

takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
  .then((data) => console.log(data))
  .catch(err => console.error(err));
}

See this github repo for full example:
https://github.com/lwansbrough/react-native-camera

Leave a Reply

Your email address will not be published. Required fields are marked *