Skip to content
Advertisement

How to use ref in a functional component (expo camera)

I’m reacting my camera as a functional component but the documentation says

To use methods that Camera exposes one has to create a component ref and invoke them using it.

but in react documentation it says that I can not use ref in a functional component.

if this the same thing as useRef? I’m trying to get the camera to take a picture and save it to my phones memory.

    <Camera
    style={{ flex: 1 }}
    type={type}
    useCamera2Api={true}
    ratio={"16:9"}

//to take a picture
    ref={ref => {
    this.camera = ref;
  }}
  >

 <TouchableOpacity
        style={{
          alignSelf: 'flex-end',
          alignItems: 'center',
              backgroundColor: 'transparent',
            }}
            onPress={() => async () => {
  if (this.camera) {
    let photo = await this.camera.takePictureAsync();
  }}
      >
        <FontAwesome
          name="camera"
          style={{ color: "#fff", fontSize: 40 }}
        />
      </TouchableOpacity>

Advertisement

Answer

You can create one variable to assign with useRef

const cameraRef = useRef(null)

And then use cameraRef in ref field like this:

<Camera 
   ref = {cameraRef} 
/>

And then in your TouchableOpacity you will do it like this:

if (cameraRef) {
   const data = await cameraRef.current.takePictureAsync();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement