React Navigation goBack() - react-native

I got some error when i have used goBack(null) method in functional component in react navigation
function Header({ titleText, navigation}) {
return (
<Appbar.Header style={styles.headerContainer}>
<Appbar.BackAction style={styles.backButton} onPress={() => navigation.goBack(null)} >
<Text style={styles.back}></Text>
</Appbar.BackAction>
<View style={styles.container}>
<Title style={styles.title}>{titleText}</Title>
</View>
</Appbar.Header>
)}

Try with useNavigation hook from #react-navigation/native
import * as React from 'react';
import { Text } from 'react-native';
import { useNavigation } from '#react-navigation/native';
function MyText() {
const navigation = useNavigation();
return <Text onPress={() => navigation.goBack()}>Go Back</Text>;
}

Related

cannot read property navigate of undefined

I am getting this error cannot read the property of navigate when try to navigate to the SignInScreen
this is the splash screen that have created
import React from 'react';
import {
View,
Text,
TouchableOpacity,
Dimensions,
StyleSheet,
StatusBar,
Image
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import LinearGradient from 'react-native-linear-gradient';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { useTheme } from '#react-navigation/native';
const SplashScreen = ({navigation}) => {
const { colors } = useTheme();
return (
<View style={styles.container}>
<StatusBar backgroundColor='#009387' barStyle="light-content"/>
<View style={styles.header}>
<Animatable.Image
animation="bounceIn"
duraton="1500"
source={require('../assets/logo.png')}
style={styles.logo}
resizeMode="stretch"
/>
</View>
<Animatable.View
style={[styles.footer, {
backgroundColor: colors.background
}]}
animation="fadeInUpBig"
>
<Text style={[styles.title, {
color: colors.text
}]}>Stay connected with everyone!</Text>
<Text style={styles.text}>Sign in with account</Text>
<View style={styles.button}>
<TouchableOpacity onPress={()=>navigation.navigate('SignInScreen')}>
<LinearGradient
colors={['#08d4c4', '#01ab9d']}
style={styles.signIn}
>
<Text style={styles.textSign}>Get Started</Text>
<MaterialIcons
name="navigate-next"
color="#fff"
size={20}
/>
</LinearGradient>
</TouchableOpacity>
</View>
</Animatable.View>
</View>
);
};
export default SplashScreen;
this is the main App.js FILE WHICH IS THE ROOT FILE
const Drawer = createDrawerNavigator();
// const [isEnabled, setIsEnabled] = React.useState(false);
export default function App() {
return (
<PaperProvider theme={PaperDarkTheme}>
<SplashScreen />
</PaperProvider>
);
}
Looks like you missed to wrap main Navigation container and then drawer this can work :
import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '#react-navigation/drawer';
import { NavigationContainer } from '#react-navigation/native';
const Drawer = createDrawerNavigator();
// const [isEnabled, setIsEnabled] = React.useState(false);
export default function App() {
return (
<PaperProvider theme={PaperDarkTheme}>
<NavigationContainer>
<Drawer.Navigator initialRouteName="splash">
<Drawer.Screen name="splash" component={SplashScreen } />
{// other Screens}
</Drawer.Navigator>
</NavigationContainer>
</PaperProvider>
);
}

Why I have an Invalid hook call when I call my function?

I have 5 button "35,17,11,8,5" when I press a button I want to add the button's value to a list, so I did that.
import React, { useState } from "react";
import { StyleSheet, Text, View, Pressable, TextInput } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
function AddtoArray(array,value){
console.log('a', 'a');
const [arrayToChange, setArrayToChange] = useState(array);
console.log('a1', 'a1');
const [valueToAdd, setValueToAdd] = useState(value);
console.log('a2', 'a2');
const newArray = () => {
setArrayToChange([...arrayToChange, value]);
};
console.log('b',newArray, 'b');
return newArray;
};
function RouletteExercice1 ({ navigation }){
const [multiplyArray, setMultiplyArray] = useState([]);
return(
<View>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'35'))}}>
<Text>35</Text>
</Pressable>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'17'))}}>
<Text>17</Text>
</Pressable>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'11'))}}>
<Text>11</Text>
</Pressable>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'8'))}}>
<Text>8</Text>
</Pressable>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'5'))}}>
<Text>5</Text>
</Pressable>
</View>
)
}
But when I press a button the app say "invalic hook call" and on the console all i have is "a a".
Can someone tell me what is the problem ? please
Your AddtoArray function is outside of your functional component, RouletteExercice1.
When you call useState, you're adding state to the functional component that you're calling useState from. You must call useState from the functional component.
That said, you don't need state for arrayToChange or valueToAdd. You're only changing the one array, and you're passing the value to the function.
import React, { useState } from "react";
import { StyleSheet, Text, View, Pressable, TextInput } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
function RouletteExercice1 ({ navigation }){
const [multiplyArray, setMultiplyArray] = useState([]);
function AddtoArray(value){
setMultiplyArray((prev) => [...prev, value])
}
return(
<View>
<Pressable onPress={() => {AddtoArray('35')}}>
<Text>35</Text>
</Pressable>
<Pressable onPress={() => {AddtoArray('17')}}>
<Text>17</Text>
</Pressable>
<Pressable onPress={() => {AddtoArray('11')}}>
<Text>11</Text>
</Pressable>
<Pressable onPress={() => {AddtoArray('8')}}>
<Text>8</Text>
</Pressable>
<Pressable onPress={() => {AddtoArray('5')}}>
<Text>5</Text>
</Pressable>
</View>
)
}

How To Call Our Own Build withNavigation In React Native 6

Help,
Firstly, did React Native 6 or 5 have withNavigation ? I cannot find it in the documentation in React Native website.
So, I found some thread that we can build our own withNavigation like this :
withNavigation.js
import React from 'react';
import { useNavigation } from '#react-navigation/native'; // not sure package name
export const withNavigation = (Component) => {
return (props) => {
const navigation = useNavigation();
return <Component navigation={navigation} {...props} />;
};
};
But I don't know how to call or use the own build withNavigation.
This is my source code :
ResultList.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';
import ResultsDetail from './ResultsDetail';
import { withNavigation } from '../helper/withNavigation';
const ResultList = ({ title, results }) => {
console.log(withNavigation.component);
return (
<View style={styles.container}>
<Text style={styles.title}>{title}</Text>
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
data={results}
keyExtractor={(results) => results.id}
renderItem={({item}) => {
return (
<TouchableOpacity onPress={() => withNavigation('ResultShowScreen')}>
<ResultsDetail results={item} />
</TouchableOpacity>
)
}}
/>
</View>
)
};
const styles = StyleSheet.create({
title: {
fontSize: 18,
fontWeight: 'bold',
marginLeft: 15,
marginBottom: 5,
},
container: {
marginBottom: 10
}
});
export default ResultList;
In here :
console.log(withNavigation.component)
it show : undefined
How to get the navigation props with our own withNavigation ?
Thank You
Since your helper function, withNavigation, is a Higher-Order Component (HoC) you have to wrap your component with it in order to be able to use it:
const ResultList = ({ title, results, navigation }) => {
return (
<View style={styles.container}>
<Text style={styles.title}>{title}</Text>
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
data={results}
keyExtractor={(results) => results.id}
renderItem={({ item }) => {
return (
// Now you can use the navigation prop inside of your component
<TouchableOpacity onPress={() => navigation.navigate('MyRoute')}>
<ResultsDetail results={item} />
</TouchableOpacity>
);
}}
/>
</View>
);
};
// withNavigation adds the navigation property to your ResultList component's properties
export default withNavigation(ResultList);
I think the reason why you can't find withNavigation inside of React Navigation 5 or 6 anymore is because they suggest you to use their built-in hooks instead. I am not sure why do you need to use a custom made HoC when you could just use the useNavigation hook. If you don't have a specific reason to use your custom HoC, the built-in hooks could simplify your code:
import { useNavigation } from '#react-navigation/native';
const ResultList = ({ title, results }) => {
const navigation = useNavigation();
return (
<View style={styles.container}>
<Text style={styles.title}>{title}</Text>
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
data={results}
keyExtractor={(results) => results.id}
renderItem={({ item }) => {
return (
// You can use the navigation property inside of your component
<TouchableOpacity onPress={() => navigation.navigate('MyRoute')}>
<ResultsDetail results={item} />
</TouchableOpacity>
);
}}
/>
</View>
);
};
export default ResultList;
As per the upgrading documentation here
React Navigation 4.x included higher order components such as
withNavigation and withNavigationFocus. Now they live in the compat
package.
The documentation says that in order to upgrade from React Navigation 4 to 5:
withNavigation HOC is moved to another package #react-navigation/compat
So, in order to use that you have to import that package first:
import { withNavigation } from '#react-navigation/compat';

React navigation giving undefined

I am trying to make a back button in react native and using navigation.goBack() in the function component but if I console the navigation then it's giving me undefined
import React from 'react';
import {
Text,
StyleSheet,
Image,
View,
Dimensions,
TouchableOpacity,
} from 'react-native';
import backIcon from '../assets/back-black.png';
const {width: SCREEN_WIDTH, height: SCREEN_HEIGHT} = Dimensions.get('window');
const TitleHeader = ({navigation, title}) => {
// console.log("hello");
return (
<View style={[styles.customHeader]}>
<View style={[styles.headerLeft]}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<Image source={backIcon} style={styles.headerIcon} />
</TouchableOpacity>
<Text style={[styles.font, styles.headerTitle]}>{title}</Text>
</View>
</View>
);
};
The rest of the code is working fine I am just getting an error in navigation so I add the important code only
React-navigation v5 provides hook useNavigation() returns the navigation prop of the screen it's inside.
Sample:
import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '#react-navigation/native';
function MyBackButton() {
const navigation = useNavigation();
return (
<Button
title="Back"
onPress={() => {
navigation.goBack();
}}
/>
);
}
In your code you need pass prop navigation to your component

recieving an error 'undefined is not an object evaluating this.props.navigation' while trying to navigate to another screen

returning this error while tying to navigate using switchnavigation.
i have tried removing this. props then returns undefined 'navigation'.
import React from 'react';
import { Text, View, Image, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { createSwitchNavigator, createAppContainer , withNavigation } from 'react-navigation';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import layout from '../../constants/LayoutStyle'
import QuoteScreen from './QuoteScreen';
const HomeScreen = () => {
return (
<View style={styles.viewStyles}>
<View style={{position: 'absolute',top: hp('50%')+wp('37.5%'),left:wp('15%'),width: wp('32.5%'),height:
wp('32.5%'),backgroundColor:'rgba(255,255,255,0.1)'}}>
<View style={{alignItems: 'center',justifyContent: 'center',flex:1}}>
<Icon name="ios-book" color="purple" size={wp('10%')}
onPress={() => this.props.navigation.navigate('Quote')}
/>
<Text style={styles.tabTextStyle}>Books</Text>
</View>
</View>
);
};
const RootStack = createSwitchNavigator(
{
Home: HomeScreen,
Quote: QuoteScreen,
}
);
const AppContainer = createAppContainer(RootStack);
export default class app extends React.Component {
render() {
return <AppContainer />
}
}
expected to complete navigation properly
HomeScreen is a functional component and hence you should not use this.props.navigation, just say props.navigation.
And If you want to use props inside the function component, then use should pass props as an argument to that functional component. Like this =>
const HomeScreen = (props) => {
return (
<View style={styles.viewStyles}>
<View style={{position: 'absolute',top:
hp('50%')+wp('37.5%'),left:wp('15%'),width: wp('32.5%'),height:
wp('32.5%'),backgroundColor:'rgba(255,255,255,0.1)'}}>
<View style={{alignItems: 'center',justifyContent: 'center',flex:1}}>
<Icon name="ios-book" color="purple" size={wp('10%')}
onPress={() => this.props.navigation.navigate('Quote')}
/>
<Text style={styles.tabTextStyle}>Books</Text>
</View>
</View>
);
};
If this does not work then pass navigation as props to HomeScreen component wherever u use, Like this =>
<HomeScreen
navigation = {this.props.navigation} // or navigation = {props.navigation}, if it is functional component
/>