0

I just started react-native and I made a multi screen android application (by using react-native-navigation. My screens are functions as shown in examples of screen navigation but now I want to use the camera in the 2nd screen.

An idea of how my code looks:

import React, {Component} from 'react';
import { Platform, StyleSheet, Text, View, ScrollView, TextInput, Button, Image } from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';

import { RNCamera, FaceDetector } from 'react-native-camera';



export default function App() {
    return (

      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen
            name="Screen1"
            component={Screen1}
          />
          <Stack.Screen name="Screen2" component={Screen2} />
        </Stack.Navigator>
      </NavigationContainer>
  );
}


function Screen1({navigation}) {
  return (
    <View style={styles.container}>
      <Button
        title="Go to screen 2"
        onPress={() => navigation.navigate('Screen2', {mode: 'dev'})} // passing parameters: mode
      />
    </View>
  );
}


function Screen2({navigation}) {
  return (
    <View>
      <RNCamera
        ref={ref => {
          this.camera = ref
        }}
        style={styles.scanner}
      />
    </View>
  );
}

I get the error: TypeError: undefined is not an object (evaluating '_this.camera=_ref3') in screen2.

Though this error does not come when I define the App as one class and put the camera on the first screen (and not be able to navigate because react-native-navigation uses functions for screens).

Apologies if I sound naive I'm new to react.

ParmuTownley
  • 957
  • 2
  • 14
  • 34

1 Answers1

0

I haven't used these packages, but it looks like an issue with your ref and use of this. I normally use class components for anything that needs a ref, so you could try writing Screen2 like this:

class Screen2 extends Component {
  camera;

  render() {
    return (
      <View>
        <RNCamera ref={ref => (this.camera = ref)} style={styles.scanner} />
      </View>
    );
  }
}

Basically when Screen2 mounts you instantiate the component with an empty member called camera. As soon as the camera component renders it'll assign a reference to itself to Screen2's camera member. And then that ref will let you manipulate your camera component directly (using this.camera).

Flagship1442
  • 1,688
  • 2
  • 6
  • 13