1. React Native
  2. Camera Switching

React Native

Camera Switching

The Vision SDK supports switching between front and back cameras on supported devices. This guide covers camera switching for both the VisionCamera and VisionSdkView components.

INFO

Platform Support

  • iOS: Fully functional - Switches between front and back cameras seamlessly
  • Android: Placeholder implementation - API is accepted but camera switching is not yet functional (awaiting VisionSDK Android support)

VisionCamera (Prop-based)

The VisionCamera component provides a simple prop-based API for camera switching using the cameraFacing prop.

Basic Implementation

        import React, { useState, useRef } from 'react';
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native';
import { VisionCamera, VisionCameraRefProps, CameraFacing } from 'react-native-vision-sdk';

function CameraSwitchExample() {
  const cameraRef = useRef<VisionCameraRefProps>(null);
  const [cameraFacing, setCameraFacing] = useState<CameraFacing>('back');

  const toggleCamera = () => {
    setCameraFacing(prev => prev === 'back' ? 'front' : 'back');
  };

  return (
    <View style={styles.container}>
      <VisionCamera
        ref={cameraRef}
        scanMode="barcode"
        cameraFacing={cameraFacing}
        onBarcodeDetected={(event) => {
          console.log('Barcode detected:', event.codes);
        }}
      />

      <TouchableOpacity
        style={styles.switchButton}
        onPress={toggleCamera}
      >
        <Text style={styles.switchText}>
           Switch to {cameraFacing === 'back' ? 'Front' : 'Back'} Camera
        </Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  switchButton: {
    position: 'absolute',
    top: 20,
    right: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 20,
  },
  switchText: {
    color: 'white',
    fontSize: 14,
    fontWeight: '600',
  },
});

      

Props

Prop Type Default Description
cameraFacing 'back' | 'front' 'back' Camera facing direction

Type Export

        import { CameraFacing } from 'react-native-vision-sdk';
// CameraFacing = 'back' | 'front'

      

VisionSdkView (Ref-based)

The VisionSdkView component uses an imperative API through the setCameraSettings method for camera switching.

Basic Implementation

        import React, { useRef, useEffect } from 'react';
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native';
import VisionSdkView, { VisionSdkRefProps } from 'react-native-vision-sdk';

function LegacyCameraSwitchExample() {
  const visionSdkRef = useRef<VisionSdkRefProps>(null);

  useEffect(() => {
    // Initialize camera settings
    visionSdkRef.current?.setCameraSettings({
      nthFrameToProcess: 10,
      cameraPosition: 1 // Start with back camera
    });
    visionSdkRef.current?.startRunningHandler();
  }, []);

  const switchToFrontCamera = () => {
    visionSdkRef.current?.setCameraSettings({
      cameraPosition: 2  // 2 = front camera
    });
  };

  const switchToBackCamera = () => {
    visionSdkRef.current?.setCameraSettings({
      cameraPosition: 1  // 1 = back camera
    });
  };

  return (
    <View style={styles.container}>
      <VisionSdkView
        ref={visionSdkRef}
        mode="barcode"
        onBarcodeScan={(event) => {
          console.log('Barcode scanned:', event);
        }}
        style={styles.camera}
      />

      <View style={styles.controls}>
        <TouchableOpacity
          style={styles.button}
          onPress={switchToBackCamera}
        >
          <Text style={styles.buttonText}> Back Camera</Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.button}
          onPress={switchToFrontCamera}
        >
          <Text style={styles.buttonText}> Front Camera</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  camera: {
    flex: 1
  },
  controls: {
    position: 'absolute',
    bottom: 40,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingHorizontal: 20,
  },
  button: {
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 20,
  },
  buttonText: {
    color: 'white',
    fontSize: 14,
    fontWeight: '600',
  },
});

      

Camera Position Values

Value Camera
1 Back camera (rear-facing)
2 Front camera (selfie)

Advanced Examples

VisionCamera with Camera Toggle Icon

        import React, { useState } from 'react';
import { TouchableOpacity, Image } from 'react-native';

function CameraWithToggleIcon() {
  const [cameraFacing, setCameraFacing] = useState<CameraFacing>('back');

  return (
    <VisionCamera
      scanMode="photo"
      cameraFacing={cameraFacing}
    >
      <TouchableOpacity
        style={{
          position: 'absolute',
          top: 50,
          right: 20,
          width: 50,
          height: 50,
          borderRadius: 25,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          justifyContent: 'center',
          alignItems: 'center',
        }}
        onPress={() => setCameraFacing(prev =>
          prev === 'back' ? 'front' : 'back'
        )}
      >
        <Text style={{ fontSize: 24 }}></Text>
      </TouchableOpacity>
    </VisionCamera>
  );
}

      

VisionSdkView with State Management

        import React, { useState, useRef, useEffect } from 'react';

function StatefulCameraSwitch() {
  const visionSdkRef = useRef<VisionSdkRefProps>(null);
  const [currentCamera, setCurrentCamera] = useState<'back' | 'front'>('back');

  useEffect(() => {
    visionSdkRef.current?.setCameraSettings({
      nthFrameToProcess: 10,
      cameraPosition: currentCamera === 'back' ? 1 : 2
    });
    visionSdkRef.current?.startRunningHandler();
  }, []);

  const toggleCamera = () => {
    const newCamera = currentCamera === 'back' ? 'front' : 'back';
    setCurrentCamera(newCamera);

    visionSdkRef.current?.setCameraSettings({
      cameraPosition: newCamera === 'back' ? 1 : 2
    });
  };

  return (
    <View style={{ flex: 1 }}>
      <VisionSdkView
        ref={visionSdkRef}
        mode="photo"
        captureMode="manual"
        style={{ flex: 1 }}
      />

      <TouchableOpacity
        onPress={toggleCamera}
        style={{
          position: 'absolute',
          bottom: 100,
          alignSelf: 'center',
          backgroundColor: '#007AFF',
          paddingHorizontal: 30,
          paddingVertical: 15,
          borderRadius: 25,
        }}
      >
        <Text style={{ color: 'white', fontWeight: 'bold' }}>
          Switch to {currentCamera === 'back' ? 'Front' : 'Back'}
        </Text>
      </TouchableOpacity>
    </View>
  );
}

      

Platform-Specific Behavior

iOS

On iOS, camera switching works seamlessly:

  • Instant switching between cameras
  • Maintains current scanning mode and settings
  • No frame drops during transition
  • Works with all scan modes (barcode, QR, OCR, photo)
        // iOS - Full support
<VisionCamera
  scanMode="barcode"
  cameraFacing={cameraFacing}
  onBarcodeDetected={handleBarcode}
/>

      

Android

On Android, the camera switching API is a placeholder:

  • API accepts the prop/parameter but doesn't switch cameras
  • Awaiting underlying VisionSDK Android implementation
  • Won't cause errors or crashes
  • Forward compatible - will work once SDK supports it
        // Android - Placeholder (not yet functional)
<VisionCamera
  scanMode="barcode"
  cameraFacing={cameraFacing} // Accepted but no effect yet
  onBarcodeDetected={handleBarcode}
/>

      
WARNING

Android Users: Camera switching is not yet functional on Android. The API is in place for forward compatibility. Your app won't crash, but the camera won't switch when the prop/method is called.


Comparison: VisionCamera vs VisionSdkView

Feature VisionCamera VisionSdkView
API Style Declarative (props) Imperative (methods)
Syntax cameraFacing={'front'} setCameraSettings({ cameraPosition: 2 })
Type Safety CameraFacing enum Numeric values (1 or 2)
Ease of Use Simple prop update Requires ref method call
React-friendly More React-like Less React-like
Recommended For new projects For existing VisionSdkView users
TIP

For new projects, we recommend using VisionCamera with its prop-based API for a more React-friendly experience.


Best Practices

  1. Always provide a UI control for camera switching - don't make users guess:

            <TouchableOpacity onPress={toggleCamera}>
      <Text>Switch Camera</Text>
    </TouchableOpacity>
    
          
  2. Show current camera state to the user:

            <Text>Current: {cameraFacing === 'back' ? 'Back' : 'Front'} Camera</Text>
    
          
  3. Handle platform differences gracefully:

            import { Platform } from 'react-native';
    
    const CameraToggle = () => (
      <TouchableOpacity
        onPress={toggleCamera}
        disabled={Platform.OS === 'android'}
      >
        <Text>
          {Platform.OS === 'android' ? ' Coming Soon' : ' Switch'}
        </Text>
      </TouchableOpacity>
    );
    
          
  4. Preserve other camera settings when switching:

            // VisionCamera - settings preserved automatically
    <VisionCamera
      cameraFacing={cameraFacing}
      enableFlash={flash}
      zoomLevel={zoom}
    />
    
    // VisionSdkView - preserve manually
    visionSdkRef.current?.setCameraSettings({
      cameraPosition: newPosition,
      nthFrameToProcess: 10, // Keep existing setting
    });
    
          

Troubleshooting

Camera doesn't switch on iOS

  • Verify the prop/method value is actually changing
  • Check device has both front and back cameras
  • Ensure camera permissions are granted for both cameras

No effect on Android

  • This is expected behavior - Android support coming soon
  • Disable the toggle button or show a "Coming Soon" message
  • Your app will automatically work once Android support is added

Camera feed freezes during switch

  • This shouldn't happen on iOS - report as a bug
  • Ensure you're not stopping/starting the camera during switch

Flash doesn't work on front camera

  • Most devices don't have front-facing flash
  • Consider adding a white screen flash effect for selfies