yihom78241
yihom78241

Reputation: 83

How to hide rendered elements in React Native?

I'm making a React Native app which uses a camera. I want the camera component to render and capture video but do not want to show the output of the camera video.

I was able to do this in React.js using the follow code -

import React, { useState, createRef } from "react";
import Webcam from "react-webcam";

function Scan () {
  const videoRef = React.createRef();

  return (
    <div>
      <Typography>
        Capturing Video
      </Typography>
      <Webcam
        align="center"
        audio={false}
        mirrored={false}
        id="img"
        ref={videoRef}
        style={{display: "none"}}
      />
    </div>
  );
};

However, in React Native (using the managed Expo flow) when I try to do the same using the Expo Camera Module, it does not work. The camera component does not capture video unless it is displayed. I have tried the following and it does not work -

import React, { useState, useEffect } from "react";
import { View } from "react-native"

import { Camera } from "expo-camera";

export function Scan () {
  const [hasPermission, setHasPermission] = useState(null);

  const handleIt = async ({ barCode }) => {
    // Code to handle barcode
  };

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === "granted");
    })();
  }, []);

  if (hasPermission === null) {
    return <View />;
  };

  return (
    <Camera
      onBarCodeScanned={handleIt}
      type={Camera.Constants.Type.front}
      style={{display: "none"}}
    />
  );
};

There is no problem with the camera permissions. It works when I set the style to flex:1 (see below code). However this renders the output as well.

<Camera
  onBarCodeScanned={handleIt}
  type={Camera.Constants.Type.front}
  style={{flex: 1}}
/>

Please let me know if you have any suggestions to make this work without displaying the camera output and hiding it.

Upvotes: 1

Views: 1215

Answers (1)

yihom78241
yihom78241

Reputation: 83

This works by setting flex along with opacity to 0. The solution which worked for me is -

style={{opacity: 0, flex:1}}

Thanks to @Sohaib, his comment was very helpful in finding the solution.

Upvotes: 1

Related Questions