Search code examples
react-nativeexpoexpo-camera

Facing issues using CameraView imported from expo-camera to set up a QR Code Scanner for a react-native expo project


I have been trying to code for a QR Code Scanner for my React Native project (using typescript). I have followed the latest documentation for expo-camera, and even though my phone prompts for permission to use the camera and the component gets rendered with no errors, my phone camera is not turning on.

Here is my QR Code Scanner component code following the doc:

import React, { useState, useEffect, useRef } from "react";
import { CameraView, useCameraPermissions } from "expo-camera";
import { View, Text, TouchableOpacity, Button } from "react-native";
import tw from "twrnc";

interface CameraFacing {
  facing: "front" | "back";
}

const QrCodeScanner: React.FC = () => {
  const [facing, setFacing] = useState<CameraFacing["facing"]>("back");
  const [permission, requestPermission] = useCameraPermissions();

  useEffect(() => {
    if (!permission) return; // Skip if permission is still loading

    if (permission.status !== "granted") {
      // Request permission if not granted or undetermined
      requestPermission();
    }
  }, [permission, requestPermission]);
  if (!permission?.granted) {
    // Camera permissions are not granted yet.
    return (
      <View style={tw`flex-1 items-center justify-center`}>
        <Text style={tw`text-center`}>
          We need your permission to show the camera
        </Text>
        <Button title="grant permission" onPress={requestPermission} />
      </View>
    );
  }

  const toggleCameraFacing = () => {
    setFacing((current) => (current === "back" ? "front" : "back"));
  };

  return (
     <View style={tw`flex-1`}>
      <CameraView style={tw`flex-1`} facing={facing}>
        <View style={tw`absolute bottom-0 right-0 pb-4 pr-4`}>
          <TouchableOpacity
            style={tw`rounded-full bg-gray-500 p-2`}
            onPress={toggleCameraFacing}
          >
            <Text style={tw`text-white text-lg`}>Flip Camera</Text>
          </TouchableOpacity>
        </View>
      </CameraView>
    </View>
  );
};

export default QrCodeScanner;

I have tried all sorts of solutions for this, including deleting node modules and re-installing them, but it isn't working. Please help.


Solution

  • The problem was with tailwind styling code (items center). When removed, it worked.