2

I am new to react native and react navigation and I get this error.

Uncaught TypeError: Cannot read properties of undefined (reading 'navigate')

I don't understand my because I am just using the same code which already worked, but now it's not working.

I am trying to make a back arrow that send you back to the MachineList screen.

//doesn't work
const AddMachineDetails = ({route}, props) => {

...

<TouchableOpacity onPress={() => props.navigation.navigate("MachinesList")}>
        <BackArrow />
 </TouchableOpacity>

So when I press my backarrow it send me this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'navigate')

Here is my Navigation file:

import MachinesList from '../components/MachinesList'
import AddMachineDetails from '../components/AddMachineDetails';

...

function MachineListStackScreen() {
    return(
        <Stack.Navigator screenOptions={{headerShown: false}}>
            <Stack.Screen name='MachinesList' component={MachinesList}/>
            <Stack.Screen name='AddMachineDetails' component={AddMachineDetails}/>
        </Stack.Navigator>
    )
}

...

I think the problem is somewhere in this code, but if not, I'll show you more of my code

Here is an example where my navigation.navigate work perfectly:

//no specific imports  (but works)

const MachinesList = (props) => {

...


<TouchableOpacity style={styles.machineBox} onPress={() => props.navigation.navigate('AddMachineDetails', {item})}>
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
owdji
  • 151
  • 2
  • 12
  • Here: `const AddMachineDetails = ({route}, props) =>` it seems to don't get the good "props" becuase the props.navigation is undefined – Elikill58 Jan 28 '22 at 12:52
  • do you have an idea of what should I do ? because I am just doing as usual (I've checked if there was any typing mistake) but this time it dosen't work – owdji Jan 28 '22 at 12:54

3 Answers3

0

The issue is here ({route}, props) =>.

You are destructuring the first argument, but there aren't other parameters passed and that's why "props" variable is undefined.

You have two solutions:

  1. Just use props:
const AddMachineDetails = (props) => {
  1. Destructure props:
const AddMachineDetails = ({route, navigation, ...props}) => {
...

<TouchableOpacity onPress={() => navigation.navigate("MachinesListDetails")}>
       <BackArrow />
</TouchableOpacity>
Giovanni Londero
  • 1,309
  • 1
  • 10
  • 20
0

You have to desctruct the props argument.

const AddMachineDetails = ({route, ...props}) => { ... }  

or

const AddMachineDetails = ({route, navigation, ...props}) => { ... }  // then straightly use the *navigation*
Ergis
  • 1,105
  • 1
  • 7
  • 18
0

Optional chaining can be useful in future to prevent errors in runtime. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining