Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 224
Bruce Mathers Avatar asked Sep 19 '25 14:09

Bruce Mathers


1 Answers

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();
like image 82
Jancer Lima Avatar answered Sep 21 '25 04:09

Jancer Lima