Fairly new to React and just following along to YouTube tutorials where I can. Having an issue with a navigation bar that I've imported into a screen. Clicking on any of the links results in an 'undefined' error.
My environment is
- React Native
- Android Development Studio (With simulator)
- VSCode to develop
Here are my files
App.js
import React, from 'react';
import { StyleSheet } from 'react-native';
// Menu and Navigation
import { NavigationContainer } from '@react-navigation/native';
import Navigator from './Screens/AppNavigator';
export default function App() {
return (
<NavigationContainer>
<Navigator />
</NavigationContainer>
);
};
AppNavigator.js
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './HomeScreen';
import ProfileScreen from './ProfileScreen';
export default function AppNavigator() {
const Stack = createStackNavigator();
return (
<Stack.Navigator initialRouteName='Home'>
<Stack.Screen name="Home" component={HomeScreen} options={{ headerShown: false }} />
<Stack.Screen name="Profile" component={ProfileScreen} options={{ headerShown: false }} />
</Stack.Navigator>
);
};
ProfileScreen.js - This has the content and the Navigation bar imported onto it.
import React, { useState } from 'react';
import { View, Text, Image, Button, TextInput } from 'react-native';
import ScreenStyles from './ScreenStyles';
import NavBar from '../components/NavBar/NavBar';
export default function ProfileScreen() {
return (
<View style={ScreenStyles.ScreenFramework}>
<View style={ScreenStyles.ScreenContainer}>
<View style={{ padding: 30 }}>
<Text style={ScreenStyles.ScreenTitle}>Your Profile Page</Text>
</View>
</View>
<View style={ScreenStyles.NavBarContainer}>
<NavBar />
</View>
</View>
);
};
NavBar.js - When clicking a link, it throws an error 'Cannot read property 'navigate' of undefined'
import React from 'react';
import { View, Text, Image, TouchableOpacity } from 'react-native';
import styles from './NavbarStyle';
export default function NavBar({ navigation }) {
return (
<View style={styles.NavBarContainer}>
<View style={styles.ImageContainer}>
<TouchableOpacity onPress={() => navigation.navigate('Home')}>
<View style={styles.ImageIcon}>
<Image
style={{ width: 40, height: 40 }}
source={require('./img/home.png')} />
</View>
</TouchableOpacity>
</View>
<View style={styles.ImageContainer}>
<TouchableOpacity onPress={() => navigation.navigate('Profile')}>
<View style={styles.ImageIcon}>
<Image
style={{ width: 40, height: 40 }}
source={require('./img/profile.png')} />
</View>
</TouchableOpacity>
</View>
</View>
);
}
I am wondering what I can do to resolve this issue?
CodePudding user response:
You need either to pass navigation as a prop in <NavBar />
or use a hook as stated here