React Native Navigation Error. How do I solve this? - react-native

In this block of code, I want to use navigation.navigate to switch between the home screen and the profile screen. But when I run the app, I get the following error: can't find variable navigation.
I've been looking for a solution, but I can't seem to find it.
Here's the code:
import 'react-native-gesture-handler';
import * as React from 'react';
import {View, Text, Button} from 'react-native';
import { NavigationContainer, StackActions } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
const Stack = createStackNavigator();
const HomeScreen = () => {
return(
<View>
<Text>Home Screen</Text>
<Button title="Go to Profile Screen" onPress={()=> navigation.navigate("Profile")}/>
</View>
);
}
const ProfileScreen = () => {
return(
<View>
<Text>Profile Screen</Text>
<Button title="Go to Home Screen" onPress={() => navigation.navigate("Home")}/>
</View>
);
}
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Profile"
component={ProfileScreen}
options={{ title: '' }}
/>
<Stack.Screen
name="Home"
component={HomeScreen}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
Thank you in advance.

You can get navigation object from props. Code example:
const HomeScreen = ({navigation}) => {
return(
<View>
<Text>Home Screen</Text>
<Button title="Go to Profile Screen" onPress={()=> navigation.navigate("Profile")}/>
</View>
);
}

Related

React-native bottom navigation with stacknavigator

I'm new to React Native and trying to learn. but I couldn't do what I wanted to do.
I have Tab Navigations and I want to Open Stack when I click the button. But I can't figure out how to do it, thanks in advance for your help.
Snack
import * as React from 'react';
import { View,Text,TouchableOpacity,Button } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
const Tab = createBottomTabNavigator();
const Stack = createNativeStackNavigator();
function Home() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Page</Text>
<Button
title="Go to Settings"
onPress={() => navigation.navigate('FeedScreen')}
/>
</View>
);
}
function FeedScreen() {
return (
<Stack.Navigator>
<Stack.Screen name="Home" component={Details} />
</Stack.Navigator>
);
}
function Details() {
return <View><Text>Details</Text></View>;
}
function Profile() {
return <View>
<Text>Profile</Text>
</View>;
}
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={Home} />
<Tab.Screen name="Profile" component={Profile} />
</Tab.Navigator>
</NavigationContainer>
);
}
Your tabs can take a StackNavigator as the component and by default it will go to the first screen in that stack when you press the tab.
edit to your code
import * as React from 'react';
import { View,Text,TouchableOpacity,Button } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
const Tab = createBottomTabNavigator();
const Stack = createNativeStackNavigator();
function Home() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Page</Text>
<Button
title="Go to Settings"
onPress={() => navigation.navigate('FeedScreen')}
/>
</View>
);
}
function Details() {
return <View><Text>Details</Text></View>;
}
function Profile() {
return <View>
<Text>Profile</Text>
</View>;
}
function FeedScreen() {
return (
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Details" component={Details} />
</Stack.Navigator>
);
}
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Feed" component={FeedScreen} />
<Tab.Screen name="Profile" component={Profile} />
</Tab.Navigator>
</NavigationContainer>
);
}
The navigation.navigate(...) part becomes a little more complicated but not too bad. See the example here. This one is basically opposite of your setup where the tabs are nested within a stack navigator.

screens are not navigating in react native

I have a login screen then from there I navigate to home screen, and on home screen there are 4 buttons Alphabets, Ch-1,Ch-2 and Ch-3, by pressing each of those buttons, I can easily navigate to correct screens but Inside Alphabet screen, I have 2 more buttons Learn and Give test But when I press those, nothing happens , i can't navigate to the respective screens plus there are no errors. I guess its nested navigation.
I might sound stupid to an expert out there :) but I am new (from scratch) to react native and navigation stuff i really have no idea what to do! Will be really thankful if someone helps!
CODE IS GIVEN BELOW:
This is my home.js (its in folder screens):
import React from "react";
import {View, StyleSheet, Text} from 'react-native';
import { TouchableOpacity } from "react-native-gesture-handler";
import { Auth } from "../services";
export default home =({navigation}) => {
return (
<View style={styles.body}>
<Text style={styles.toptext}>
Merheba!
</Text>
<TouchableOpacity onPress={() => navigation.navigate('alphabets')}
style={styles.button}
>
<Text style={styles.buttontext}>Alphabets</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('ch1')}
style={styles.button}
>
<Text style={styles.buttontext}>Chapter 1</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('ch2')}
style={styles.button}
>
<Text style={styles.buttontext}>Chapter 2</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('ch3')}
style={styles.button}
>
<Text style={styles.buttontext}>Chapter 3</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => Auth.signOut()}
style={styles.button}
>
<Text style={styles.buttontext}>Sign Out</Text>
</TouchableOpacity>
</View>
)
}
This is index.js from screens folder:
export {default as home} from './home';
export {default as login} from './login';
export {default as forgotp} from './login';
export {default as signup} from './signup';
export {default as alphabets} from './alphabets';
export {default as alphl} from './alphl';
export {default as alpht} from './alpht';
export {default as ch1} from './ch1';
export {default as ch2} from './ch2';
export {default as ch3} from './ch3';
This is alphabets.js from screens folder:
import { NavigationContainer } from "#react-navigation/native";
import React from "react";
import {View, StyleSheet, Text} from 'react-native';
import { TouchableOpacity } from "react-native-gesture-handler";
export default alphabets =({navigation}) => {
return (
<View style={styles.body}>
<Text style={styles.toptext}>
Merheba!
</Text>
<TouchableOpacity onPress={() => navigation.navigate('alphl')}
style={styles.button}
>
<Text style={styles.buttontext}>Learning Sheet</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('alpht')}
style={styles.button}
>
<Text style={styles.buttontext}>Give Test</Text>
</TouchableOpacity>
</View>
)
}
AppNavigation.js from navigation folder:
import React from 'react';
import { createStackNavigator } from '#react-navigation/stack';
import home from '../screens/home';
import alphabets from '../screens/alphabets';
import ch1 from '../screens/ch1';
import ch2 from '../screens/ch2';
import ch3 from '../screens/ch3';
const stack=createStackNavigator();
export default AppNavigator = () => {
return(
<stack.Navigator
screenOptions={{
headerShown: null
}}
>
<stack.Screen name="home" component={home} />
<stack.Screen name="alphabets" component={alphabets} />
<stack.Screen name="ch1" component={ch1}/>
<stack.Screen name="ch2" component={ch2} />
<stack.Screen name="ch3" component={ch3} />
</stack.Navigator>
)
}
AlphNavigator.js from navigation folder:
import React from 'react';
import { createStackNavigator } from '#react-navigation/stack';
import alphl from '../screens/alphl';
import alpht from '../screens/alpht';
const stack=createStackNavigator();
export default AlphNavigator = () => {
return(
<stack.Navigator
screenOptions={{
headerShown: null
}}
>
<stack.Screen name="alphl" component={alphl} />
<stack.Screen name="alpht" component={alpht} />
</stack.Navigator>
)
}
& lastly index.js from navigation folder:
import React, {useState, useEffect} from 'react';
import { NavigationContainer } from '#react-navigation/native';
import AppNavigator from './AppNavigator';
import AuthNavigator from './AuthNavigator';
import auth from '#react-native-firebase/auth';
export default AppContainer = () => {
// Set an initializing state whilst Firebase connects
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
// Handle user state changes
function onAuthStateChanged(user) {
setUser(user);
if (initializing) setInitializing(false);
}
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
if (initializing) return null;
return(
<NavigationContainer>
{user ? <AppNavigator/> : <AuthNavigator/>}
</NavigationContainer>
)
}
You aren't defining your "AlphNavigator" in your "AppNavigator".
You should do this inside your AppNavigator:
export default AppNavigator = () => {
return(
<stack.Navigator
screenOptions={{
headerShown: null
}}
>
<stack.Screen name="home" component={home} />
<stack.Screen name="alphabets" component={alphabets} />
<stack.Screen name="alph" component={ AlphNavigator } /> /*here add your AlpNavigator*/
<stack.Screen name="ch1" component={ch1}/>
<stack.Screen name="ch2" component={ch2} />
<stack.Screen name="ch3" component={ch3} />
</stack.Navigator>
)}
It's normal that you do not have any error in this case, because React Navigation does not mark you as an error if a screen does not exist.
The above could be solved if you were using TypeScript.
So now, in order to access to nested navigation screens you should use:
navigation.navigate('alph', { screen: 'alphl' })
The first parameter is the name of the stack navigation, and the second one is an object with the name of the screen inside to this nested navigation.

problem using react navigation in react native(getting undefined error)

I am trying to use the navigation in react-native but it gives me this error TypeError: undefined is not an object (evaluating 'navigation. navigate') I tried so hard but I can't resolve it.
this is my componnet code:
function profile(props,{navigation}) {
const {currentUser,posts} = props;
//console.log({currentUser,posts})
return (
<View style={{flex:1,marginTop:40,}}>
<View style={{flexDirection:'row', alignItems:'center', justifyContent:'center'}}>
<View>
<Image source={require('./Un2titled.png')} style={{height:150 , width:150 ,marginLeft:20}}/>
</View>
<View style={{margin:20}}>
<Text style={{marginLeft:70, fontSize:20}}>{currentUser.name}</Text>
<Text style={{marginLeft:15, fontSize:20,marginTop:10}}>{currentUser.email}</Text>
<TouchableOpacity onPress={() => navigation.navigate('Profilephoto')} style={{ marginLeft:40,marginTop:10, fontSize:20,width:100,elevation: 8,backgroundColor: "#0088cc",borderRadius: 10,paddingVertical: 10,paddingHorizontal: 12}}>
<Text style={{color:"white"}}>تعویض عکس</Text>
</TouchableOpacity>
<TouchableOpacity style={{ marginLeft:30,marginTop:10, fontSize:10,width:120,elevation: 8,backgroundColor: "#cc0000",borderRadius: 10,paddingVertical: 10,paddingHorizontal: 12}}>
<Text style={{color:"white"}}>خروج از حساب</Text>
</TouchableOpacity>
</View>
</View>
and this is my app.js code:
import React , {Component} from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import Landingscreen from './components/auth/Landing'
import registerscreen from './components/auth/Register'
import loginscreen from './components/auth/Login'
import Mainscreen from './components/main'
import Homescreen from './components/main/Home'
import Savescreen from './components/main/Save'
import ProfilePhotoscreen from './components/main/Profilephoto'
...
return(
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator initialRouteName="main">
<Stack.Screen name="mainscreen" component={Mainscreen} options={{headerShown: false}}/>
<Stack.Screen name="save" component={Savescreen} navigation={this.props.navigation} />
<Stack.Screen name="Home" component={Homescreen} navigation={this.props.navigation} />
<Stack.Screen name="ProfilePhoto" component={ProfilePhotoscreen} navigation={this.props.navigation} />
</Stack.Navigator>
</NavigationContainer>
</Provider>
I think it comes from the way you get the navigation variable.
I would do this:
function profile(props) {
const {currentUser, posts, navigation} = props;
...
}

Bottom tab bar should not occur anywhere but only on the first initial screen that renders via Webview in React Native

I have a webview component in my project, where the flow being =>
The bottomTabBar opens the initial screen of the url that is given to Webview source prop, which should remain, when any link is clicked on the webview and it moves to another screen, the bottomtabbar should not come up.
Below is my WebviewScreen code :
import React, {Component} from 'react';
import {WebView} from 'react-native-webview';
import {View, SafeAreaView, ActivityIndicator} from 'react-native';
export default class ConsultationHomeScreen extends Component {
renderLoadingView = () => {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<ActivityIndicator size="large" />
</View>
);
};
render() {
const {url} = this.props.route.params;
return (
<SafeAreaView style={{flex: 1}}>
<WebView
source={{uri: url}}
renderLoading={this.renderLoadingView}
startInLoadingState={true}
ref={(ref) => {
this.webview = ref;
}}
onNavigationStateChange={(event) => {
if (event.url !== url) {
this.webview.stopLoading();
}
}}
/>
</SafeAreaView>
);
}
}
And Appnavigation.js
import * as React from 'react';
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
import {createBottomTabNavigator} from '#react-navigation/bottom-tabs';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import LoginScreen from '../screens/authentication/LoginScreen';
import OtpScreen from '../screens/authentication/OtpScreen';
import AddChild from '../screens/Child/AddChild';
import AcceptInviteScreen from '../screens/AcceptInviteScreen';
import ConsultationHomeScreen from '../screens/ConsultationHomeScreen';
import HomeScreen from '../screens/HomeScreen/HomeScreen';
import PlansScreen from '../screens/PlansScreen';
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
function BottomTabBar() {
return (
<Tab.Navigator
lazy={false}
tabBarOptions={{
labelStyle: {
color: '#FF1493',
fontSize: 15,
},
}}>
<Tab.Screen
name="Home"
component={HomeScreen}
options={{
tabBarIcon: () => {
<MaterialIcon name="home" color="#FF1493" size={20} />;
},
}}
/>
<Tab.Screen
name="Consult"
component={ConsultationHomeScreen}
initialParams={{
url: 'some link',
}}
/>
<Tab.Screen name="Plans" component={PlansScreen} />
</Tab.Navigator>
);
}
export default function AppNavigation() {
return (
<NavigationContainer>
<Stack.Navigator headerMode="none">
<Stack.Screen name="login" component={LoginScreen} />
<Stack.Screen name="otp" component={OtpScreen} />
<Stack.Screen name="addchild" component={AddChild} />
<Stack.Screen
name="acceptinvitescreen"
component={AcceptInviteScreen}
/>
<Stack.Screen name="home" component={BottomTabBar} />
</Stack.Navigator>
</NavigationContainer>
);
}
However, am unable to remove the bottomtabbar,could anyone please suggest how should I implement this behaviour?
Step1-> Webview initial screen renders and has bottomtabtabr
Step2-> Link clicked on the initial screen and navigates to next screen handled by web source
Step3->Bottom tab bar should not occur anywhere but only on the first initial screen
Please,any suggestion would be appreciated and let me know if anything else is required for better understanding.
I tested this modification in your source code and it works like a charm.
GIT difference in WebviewScreen.js :
## -23,6 +23,7 ## export default class ConsultationHomeScreen extends Component {
}}
onNavigationStateChange={(event) => {
if (event.url !== url) {
+ this.props.navigation.setOptions({ tabBarVisible: false });
this.webview.stopLoading();
}
}}
Let me know if you have any issue.

can't find variable navigation in other component in react-native

This is my App.js
import React from "react";
import Menu from "./components/Menu";
import HomeScreen from "./views/HomeScreen";
import SecondScreen from "./views/SecondScreen";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
const Stack = createStackNavigator();
export default function App() {
return (
<Container>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
/>
<Stack.Screen name="Second" component={SecondSCreen} />
</Stack.Navigator>
</NavigationContainer>
<Menu></Menu>
</Container>
);
}
It works, because it shows the HomeScreen on default, but I want to navigate to the second screen via the Menu-component:
import React from "react";
import { View, Text, TouchableOpacity } from "react-native";
class Menu extends React.Component {
render() {
return (
<View>
<TouchableOpacity
onPress={() => {
alert("Hi");
}}
>
<Text>HomeScreen</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
navigation.navigate("Second");
}}
>
<Text>Screen 2</Text>
</TouchableOpacity>
</View>
);
}
}
export default Menu;
The component is visible, but when I click on the second button I expect the SecondScreen to be openend.
But I get this error:
Can't find variable: navigation
What am I missing?
You should use the navigationRef for this scenario, as your menu is outside the navigation container
import { NavigationContainer } from '#react-navigation/native';
import { navigationRef } from './RootNavigation';
export default function App() {
return (
<Container>
<NavigationContainer ref={navigationRef}>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
/>
<Stack.Screen name="Second" component={SecondSCreen} />
</Stack.Navigator>
</NavigationContainer>
<Menu></Menu>
</Container>
);
}
// RootNavigation.js
import * as React from 'react';
export const navigationRef = React.createRef();
export function navigate(name, params) {
navigationRef.current?.navigate(name, params);
}
In menu js,
import {navigate} from 'RootNavigation';
class Menu extends React.Component {
render() {
return (
<View>
<TouchableOpacity
onPress={() => {
alert("Hi");
}}
>
<Text>HomeScreen</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
navigate("Second");
}}
>
<Text>Screen 2</Text>
</TouchableOpacity>
</View>
);
}
}