Go from child navigation to parent navigation - react-native

I have two NavigationContainer. What I want is when I am on the SignIn screen go to the MainPage. And the problem goes when I am in MainPage > Profile. The Button Logout does not go to the SignIn Screen.
App.js
import React from "react";
import {SignIn} from './src/screen/authentication/signIn'
import {SignUp} from "./src/screen/authentication/signUp";
import {MainPage} from "./src/screen/drawer";
import {createStackNavigator} from "#react-navigation/stack";
import {NavigationContainer} from "#react-navigation/native";
const Stack = createStackNavigator();
class App extends React.Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="SignIn" headerMode={null}>
<Stack.Screen name="SignIn" component={SignIn} />
<Stack.Screen name="SignUp" component={SignUp} />
<Stack.Screen name="Home" component={MainPage} />
</Stack.Navigator>
</NavigationContainer>
);
}
}
drawer.js
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import {createDrawerNavigator} from '#react-navigation/drawer';
import {Dashboard} from "./dashboard/dashboard";
import {AddWidget} from "./addWidget/addWidget";
import {Profile} from "./profile/profile";
const Drawer = createDrawerNavigator();
export function MainPage({navigation}) {
return(
<NavigationContainer independent={true}>
<Drawer.Navigator>
<Drawer.Screen name="Dashboard" component={Dashboard} />
<Drawer.Screen name="Add widget" component={AddWidget} />
<Drawer.Screen name="Profile" component={Profile} initialParams={{navigation: () => navigation.navigate('SignIn')}} />
</Drawer.Navigator>
</NavigationContainer>
);
}
Profile.js
import * as React from 'react';
import {Button, Text, View} from "react-native";
import {useHistory} from "react-router-dom";
import {styles} from "./styles"
export function Profile({navigation}) {
const history = useHistory();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={styles.title}>Username</Text>
<Button title="Logout" onPress={() => navigation.navigation} />
</View>
);
}

A trick that I found is printing props with console.log and finding the function inside the object.
So what I did is changing the name of initialparams from Profile, navigation to parentNaivgation. And also removing ({navigation}) to (props) in the Profile component.
At the end, the route to finding the function navigation was props.route.params.parentNavigation.navigate("SignIn")

you should be able to just do this:
<Button title="Logout" onPress={() => navigation.navigate("SignIn")} />
if the above doesn't work, you can try this:
import * as React from 'react';
import {Button, Text, View} from "react-native";
import {useHistory} from "react-router-dom";
import { useNavigation } from '#react-navigation/native';
import {styles} from "./styles"
export function Profile() {
const history = useHistory();
const navigation = useNavigation();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={styles.title}>Username</Text>
<Button title="Logout" onPress={() => navigation.navigate("SignIn")} />
</View>
);
}

Related

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.

How to pass data through stack navigation to a specific screen on react native tabs?

I'm creating a bottom tabs in react native, which will have two screens Home and News.
But first, user will need to Sign In and the users data will be passed from the login screen to Home screen. How do i pass those data. By using
navigation.navigate('Home', {Name: Name});
I can successfuly retrieve the data in Homescreen, if I just use two screen(Login and Home in a stack). However, when I change to navigate to the tabs(which includes Home and News), it doesnt work with error 'Undefined is not an object(evaluating 'route.params.Name'.
May you guys show me which part did I miss?
Here's the app.js code.
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import HomeScreen from './homescreen';
import NewsScreen from './newsscreen';
import LoginScreen from './loginscreen';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { createStackNavigator } from '#react-navigation/stack';
const Tab = createBottomTabNavigator();
function MyTabs() {
return (
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="News" component={NewsScreen} />
</Tab.Navigator>
);
}
const LoginStack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<LoginStack.Navigator screenOptions={{headerShown: false}}
initialRouteName="Login">
<LoginStack.Screen name="Login"component={LoginScreen}/>
<LoginStack.Screen name="MyTabs" component={MyTabs} />
</LoginStack.Navigator>
</NavigationContainer>
);
}
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Following is the homescreen code:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function HomeScreen({route, navigation}) {
var Name = route.params.Name;
return (
<View style={styles.container}>
<Text>{Name}</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
And finally here's the login code:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
export default function LoginScreen({navigation}) {
const Name = 'Boy';
const login = () => {
navigation.navigate('MyTabs', {Name: 'Boy'});}
return (
<View style={styles.container}>
<Text>LoginScreen</Text>
<TouchableOpacity
onPress={login}
><Text
>LOGIN</Text>
</TouchableOpacity>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
})
I'm trying to learn how to pass data from a screen to another screen, in which the screen is located inside a tab stack. I hope you guys can understand the question and provide me with your opinion and solution. Thanks.
Output:
It needed just this little modification in MyTabs component:
function MyTabs({ navigation, route }) {
const { name } = route.params;
console.log(name);
return (
<Tab.Navigator>
<Tab.Screen
name="Home"
component={() => <HomeScreen name={route.params.name} />}
/>
<Tab.Screen name="News" component={NewsScreen} />
</Tab.Navigator>
);
}
Here is the working solution:
App.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 { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import HomeScreen from './home';
import NewsScreen from './newscreen';
import LoginScreen from './login';
// You can import from local files
const Tab = createBottomTabNavigator();
function MyTabs({ navigation, route }) {
const { name } = route.params;
console.log(name);
return (
<Tab.Navigator>
<Tab.Screen
name="Home"
component={() => <HomeScreen name={route.params.name} />}
/>
<Tab.Screen name="News" component={NewsScreen} />
</Tab.Navigator>
);
}
const LoginStack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<LoginStack.Navigator
screenOptions={{ headerShown: true }}
initialRouteName="Login">
<LoginStack.Screen name="Login" component={LoginScreen} />
<LoginStack.Screen name="MyTabs" component={MyTabs} />
</LoginStack.Navigator>
</NavigationContainer>
);
}
export default App;
LoginScreen
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import React from "react";
export default function LoginScreen({ navigation }) {
const Name = 'Name From Login Screen';
const login = () => {
console.log("hi");
navigation.navigate('MyTabs', { name : Name });
}
return (
<View style={styles.container}>
<View style={styles.bottomView}>
<TouchableOpacity onPress={login} style={styles.button}>
<Text style={styles.textStyle}>LOGIN</Text>
</TouchableOpacity>
</View>
</View>
);
}
Home.js
import { Text, View, StyleSheet } from 'react-native';
import React from "react";
export default function HomeScreen({route, navigation, name}) {
console.log("***",name)
return (
<View style={styles.container}>
<Text style={styles.name}>{name}</Text>
</View>
);
}
Working Expo Snack example.
It's a little complicated to explain react native screens once you start combining bottomtabnavigator and stack navigator and even drawernavigation.
you may need to create stack navigation inside tab navigation like this.
//creating a separate stack within your tab
const HomeStack = createStackNavigator()
const HomeStackNavigator = () => {
return (
<HomeStack.Navigator screenOptions={{headerShown: false}}
initialRouteName="HomeScreen">
<HomeStack.Screen name="Home"component={HomeScreen}/>
</HomeStack.Navigator>
)
}
const Tab = createBottomTabNavigator();
function MyTabs() {
return (
<Tab.Navigator initialRouteName="HomeStackNavigator">
<Tab.Screen name="HomeStackNavigator" component={HomeStackNavigator} />
<Tab.Screen name="News" component={NewsScreen} />
</Tab.Navigator>
);
}
I believe, different navigators doesn't really talk to each other well. If you are using different navigator be prepare to nest stack navigators inside them.
The idea is, the parent of each display component should be a stack navigator. This will also allow you to better control your screenOptions.

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.

how to access navigation outside of navigationcontainer

here I am trying to add navigation to my react-native project, the button register should navigate to the success page component but only issue is the button register exists out of the navigation container
here I am trying to access "navigation" outside of navigation container
here's the navigation container:
import * as React from 'react';
import { Text, View, StyleSheet,Image,TouchableHighlight,TextInput,
Button, } from 'react-native';
import Constants from 'expo-constants';
import logo from './assets/logo4.png'
import logo2 from './assets/CFA_approved_prep_provider_RGB.png'
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { enableScreens } from 'react-native-screens';
import { Component } from 'react';
import * as Font from 'expo-font';
import { useRef } from "react";
import logo3 from './assets/logo3.png'
enableScreens();
const Stack = createStackNavigator();
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const navigationRef = useRef(null)
return (
<View style={{flex: 1,
justifyContent: 'center',
backgroundColor:'white',}}>
<NavigationContainer ref={navigationRef}>
<Stack.Navigator initialRouteName="SplashScreen">
<Stack.Screen name="SplashScreen" component={SplashScreen} />
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={Details} />
<Stack.Screen name="SuccessPage" component={SuccessPage} />
</Stack.Navigator>
</NavigationContainer>
</View>
here I am trying to access it like that:
<View style={[{ width: "90%", margin: 10 }]}>
<Button
onPress={() => navigationRef.current.navigate("SuccessPage")}
title="Register"
/>
</View>
that's the error:
screenshot here
any idea what else can be done?

React Native - Update text after clicking button

I want to update the text after clicking button.
But couldn't find a way to do this.
The code is like:
import * as React from 'react';
import { View, Button, Text } from 'react-native';
import { NavigationContainer, CommonActions } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
function HomeScreen({ navigation }) {
const state = {
user: 'test',
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>{state.user}'s profile</Text>
<Button
title="Change user param"
onPress={() =>
navigation.dispatch({
...CommonActions.setParams({ user: 'Wojtek' }),
})
}
/>
</View>
);
}
const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
Expo example
I've tried navigation.setParams() and this.setState(), they couldn't work with the code I attached above.
You have to use hooks in functional components. So the code would be something like this:
import * as React from 'react';
import { View, Button, Text } from 'react-native';
import { NavigationContainer, CommonActions } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
function HomeScreen({ navigation }) {
const [user, setUser] = React.useState('test');
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>{user}'s profile</Text>
<Button
title="Change user param"
onPress={() => setUser("keidakira") }
/>
</View>
);
}
const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
Check it's working at Expo Link