How to access navigation in app.js react native? - react-native

I am creating a react native app, I want to be able to go straight to the homepage if login info is stored in async storage. However, I can't work out how to get navigate to work in app.js!
Error: Coulden't find a navigation object. Is your component inside a NavigationContainer?
App.js snippet:
import {useNavigation, NavigationContainer} from '#react-navigation/native';
const Stack = createNativeStackNavigator();
const App = () => {
const navigation = useNavigation();
useEffect(() => {
const getLoginData = async () => {
try {
const loginData = await AsyncStorage.getItem('loginData');
const coachingScreenCompleted = await AsyncStorage.getItem(
'CoachingScreenCompleted',
);
if (loginData !== undefined) {
coachingScreenCompleted
? navigation.navigate('LoggedInView', JSON.parse(loginData))
: navigation.navigate('CoachingScreen');
}
} catch (err) {
console.log(err);
}
};
getLoginData().catch(console.error);
}, []);
Full code of app.js
import React, {useState, useEffect} from 'react';
import {
DarkTheme as NavigationDarkTheme,
DefaultTheme as NavigationDefaultTheme,
} from '#react-navigation/native';
import {createNativeStackNavigator} from '#react-navigation/native-stack';
import LoginScreen from './screen/LoginScreen';
import ForgottenPasswordStepOne from './screen/ForgottenPasswordScreens/ForgottenPasswordStepOne';
import ForgottenPasswordStepTwo from './screen/ForgottenPasswordScreens/ForgottenPasswordStepTwo';
import ForgottenPasswordStepThree from './screen/ForgottenPasswordScreens/ForgottenPasswordStepThree';
import RegisterHalfMemberStepTwo from './screen/RegisterScreens/RegisterHalfMemberStepTwo';
import RegisterHalfMemberStepThree from './screen/RegisterScreens/RegisterHalfMemberStepThree';
import RegisterStepOne from './screen/RegisterScreens/RegisterStepOne';
import RegisterStepTwo from './screen/RegisterScreens/RegisterStepTwo';
import RegisterStepThree from './screen/RegisterScreens/RegisterStepThree';
import {
adaptNavigationTheme,
MD3LightTheme,
Provider as PaperProvider,
} from 'react-native-paper';
import ThemeContext, {isDarkColorScheme} from './helpers/ThemeContext';
import useColours from './helpers/useColours';
import {createMaterialBottomTabNavigator} from '#react-navigation/material-bottom-tabs';
import {
customDarkColors,
customFontThemes,
customLightColors,
} from './helpers/theme';
import SplashScreen from 'react-native-splash-screen';
import {YellowBox} from 'react-native';
import CoachingCarousel from './screen/CoachingScreen';
import LoggedInView from './LoggedInView';
import AsyncStorage from '#react-native-async-storage/async-storage';
import {useNavigation, NavigationContainer} from '#react-navigation/native';
const Stack = createNativeStackNavigator();
const App = () => {
const navigation = useNavigation();
useEffect(() => {
const getLoginData = async () => {
try {
const loginData = await AsyncStorage.getItem('loginData');
const coachingScreenCompleted = await AsyncStorage.getItem(
'CoachingScreenCompleted',
);
if (loginData !== undefined) {
coachingScreenCompleted
? navigation.navigate('LoggedInView', JSON.parse(loginData))
: navigation.navigate('CoachingScreen');
}
} catch (err) {
console.log(err);
}
};
getLoginData().catch(console.error);
}, []);
useEffect(() => {
YellowBox.ignoreWarnings(['VirtualizedLists should never be nested']);
}, []);
useEffect(() => {
SplashScreen.hide();
}, []);
const colours = useColours();
const [darkMode, setDarkMode] = useState(isDarkColorScheme);
const toggleTheme = () => {
setDarkMode(!darkMode);
};
const {LightTheme, DarkTheme} = adaptNavigationTheme({
light: NavigationDefaultTheme,
dark: NavigationDarkTheme,
});
const CombinedDefaultTheme = {
...MD3LightTheme,
...LightTheme,
colors: {
...MD3LightTheme.colors,
...LightTheme.colors,
...customLightColors,
},
fonts: {
...MD3DarkTheme.fonts,
...customFontThemes,
},
};
const CombinedDarkTheme = {
...MD3DarkTheme,
...DarkTheme,
colors: {
...MD3DarkTheme.colors,
...DarkTheme.colors,
...customDarkColors,
},
fonts: {
...MD3DarkTheme.fonts,
...customFontThemes,
},
};
let theme = darkMode ? CombinedDarkTheme : CombinedDefaultTheme;
return (
<ThemeContext.Provider value={{darkMode, toggleTheme}}>
<PaperProvider theme={theme}>
<NavigationContainer theme={theme}>
<Stack.Navigator
screenOptions={{
headerShown: false,
}}>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen
name="ForgottenPasswordStepOne"
component={ForgottenPasswordStepOne}
options={{
title: '',
headerShown: true,
headerShadowVisible: false,
headerTintColor: colours.outlineVariant,
headerStyle: {
backgroundColor: colours.lightModeBackground,
},
}}
/>
<Stack.Screen
name="ForgottenPasswordStepTwo"
component={ForgottenPasswordStepTwo}
options={{
title: '',
headerShown: true,
headerShadowVisible: false,
headerTintColor: colours.outlineVariant,
headerStyle: {
backgroundColor: colours.lightModeBackground,
},
}}
/>
<Stack.Screen
name="ForgottenPasswordStepThree"
component={ForgottenPasswordStepThree}
options={{
title: '',
headerShown: true,
headerShadowVisible: false,
headerTintColor: colours.outlineVariant,
headerStyle: {
backgroundColor: colours.lightModeBackground,
},
}}
/>
<Stack.Screen
name="RegisterHalfMemberStepTwo"
component={RegisterHalfMemberStepTwo}
options={{
title: '',
headerShown: true,
headerShadowVisible: false,
headerTintColor: colours.outlineVariant,
headerStyle: {
backgroundColor: colours.lightModeBackground,
},
}}
/>
<Stack.Screen
name="RegisterHalfMemberStepThree"
component={RegisterHalfMemberStepThree}
options={{
title: '',
headerShown: true,
headerShadowVisible: false,
headerTintColor: colours.outlineVariant,
headerStyle: {
backgroundColor: colours.lightModeBackground,
},
}}
/>
<Stack.Screen
name="RegisterStepOne"
component={RegisterStepOne}
options={{
title: '',
headerShown: true,
headerShadowVisible: false,
headerTintColor: colours.outlineVariant,
headerStyle: {
backgroundColor: colours.lightModeBackground,
},
}}
/>
<Stack.Screen
name="RegisterStepTwo"
component={RegisterStepTwo}
options={{
title: '',
headerShown: true,
headerShadowVisible: false,
headerTintColor: colours.outlineVariant,
headerStyle: {
backgroundColor: colours.lightModeBackground,
},
animation: 'slide_from_right',
}}
/>
<Stack.Screen
name="RegisterStepThree"
component={RegisterStepThree}
options={{
title: '',
headerShown: true,
headerShadowVisible: false,
headerTintColor: colours.outlineVariant,
headerStyle: {
backgroundColor: colours.lightModeBackground,
},
animation: 'slide_from_right',
}}
/>
<Stack.Screen
name="CoachingScreen"
component={CoachingCarousel}
options={{
headerShown: false,
}}
/>
<Stack.Screen name="LoggedInView" component={LoggedInView} />
</Stack.Navigator>
{/* {mounted && <NotificationHandler />} */}
</NavigationContainer>
</PaperProvider>
</ThemeContext.Provider>
);
};
export default App;

Related

react-native navigation. Drawer not opening after package update

I am make using react-native. I recently had to update my react-navigation package to version 6. The issue is my drawer will no longer open and I cannot figure out how to fix it.
This is may code for my navigation:
import React from 'react';
import { createDrawerNavigator } from '#react-navigation/drawer';
import { createStackNavigator } from '#react-navigation/stack';
import { StyleSheet, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/dist/FontAwesome5';
import IonIcon from 'react-native-vector-icons/dist/Ionicons';
import { useNavigation } from '#react-navigation/native';
import { HomeScreen } from '../../screens/app/home/home.screen';
import HistoryScreen from '../../screens/app/history/history.screen';
import { SignoffScreen } from '../../screens/app/signoff/signoff.screen';
import NotificationsScreen from '../../screens/app/notifications/notifications.screen';
import useTheme from '../../theme/hooks/useTheme';
import { AppStackList, AppStackProps, DrawerList } from './types';
import { Colors } from '../../theme/Variables';
import CustomDrawerContent from '../../components/molecules/custom-drawer';
import { common } from '../../theme/Common';
import { FormScreen } from '../../screens/app/form/form.screen';
import { Menu } from '../../assets';
const AppStack = createStackNavigator<AppStackList>();
const Drawer = createDrawerNavigator<DrawerList>();
const renderIcon = (name: string, ion: boolean) => {
if (ion) {
return <IonIcon name={name} style={styles.iconStyle} />;
}
return <Icon name={name} style={styles.iconStyle} />;
};
const NotificationsNavigator = () => {
const { Gutters } = useTheme();
const navigation = useNavigation<AppStackProps>();
return (
<TouchableOpacity
style={(common.navIconStyle, Gutters.regularRMargin)}
delayPressIn={0}
onPress={navigation.navigate('Notifications', { screen: 'NotificationsScreen' })}
>
<IonIcon name="notifications-outline" style={common.navIconStyle} />
</TouchableOpacity>
);
};
const MenuNavigator = () => {
const navigation = useNavigation<AppStackProps>();
return (
<TouchableOpacity>
<Menu name="notifications-outline" style={common.navIconStyle} />
</TouchableOpacity>
);
};
const historyDrawerOptions = {
headerShown: false,
title: '',
drawerIcon: () => renderIcon('tasks', false),
headerTintColor: Colors.black,
headerRight: NotificationsNavigator,
};
const AppNavigator = () => {
const { Custom } = useTheme();
return (
<AppStack.Navigator screenOptions={Custom.globalNavigatorScreenOptions}>
<AppStack.Screen
name="App Home"
component={DrawerNavigator}
options={{ headerShown: false }}
/>
<AppStack.Screen
name="NotificationsScreen"
component={NotificationsScreen}
options={{ headerShown: false }}
/>
<AppStack.Screen name="FormScreen" component={FormScreen} options={{ headerShown: false }} />
<AppStack.Screen
name="SignoffScreen"
component={SignoffScreen}
options={{ headerShown: false }}
/>
</AppStack.Navigator>
);
};
const DrawerNavigator = () => (
<Drawer.Navigator
drawerStyle={styles.drawerStyle}
drawerContentOptions={{
activeTintColor: Colors.primary,
inactiveTintColor: Colors.white,
labelStyle: {
color: Colors.white,
},
}}
drawerContent={() => <CustomDrawerContent />}
>
<Drawer.Screen
name="Home"
component={HomeScreen}
options={{
headerShown: true,
headerTitle: '',
headerTransparent: true,
headerStyle: {
height: 120,
backgroundColor: '#fff',
},
headerTitleAlign: 'center',
headerTintColor: '#002C5F',
headerRight: NotificationsNavigator,
headerRightContainerStyle: {
width: 100,
marginRight: 8,
},
headerLeft: MenuNavigator,
drawerActiveTintColor: Colors.white,
drawerInactiveTintColor: Colors.white,
drawerLabelStyle: { fontSize: 15 },
}}
/>
<Drawer.Screen name="History" component={HistoryScreen} options={historyDrawerOptions} />
</Drawer.Navigator>
);
export default AppNavigator;
The draw was working before the update but now after it wont open? My NotificationsNavigator will also not open to its screen. Can anyone help???

React Navigation - trying to hide tab-bar on on certain screens

I am trying to hide the tab bar on the first screen, but nothing I do seems to work.
If I re-render the screen then it disappears, but everytime I load the app again it will be there.
After looking online I found some workarounds and it work hiding the tab bar on the screen that I want it to hide, all except for the StartScreen.
Please can someone give me an idea of what I need to do to hide it on the StartScreen?
Thank you.
import React from "react";
import {
NavigationContainer,
getFocusedRouteNameFromRoute,
} from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import { createBottomTabNavigator } from "#react-navigation/bottom-tabs";
import { Ionicons } from "#expo/vector-icons";
import StartScreen from "../screens/StartScreen";
import LoginScreen from "../screens/LoginScreen";
import SignupScreen from "../screens/SignupScreen";
import FindPropertyScreen from "../screens/FindPropertyScreen";
import FindAddressManuallyScreen from "../screens/FindAddressManuallyScreen";
import PropertyDetailsScreen from "../screens/PropertyDetailsScreen";
import DashboardScreen from "../screens/DashboardScreen";
import HomeReviewScreen from "../screens/HomeReviewScreen";
import ContractorScreen from "../screens/ContractorScreen";
import TestScreen from "../screens/TestScreen";
import FinanceScreen from "../screens/FinanceScreen";
export default function Navigator() {
const HomeStack = createStackNavigator();
const HomeStackScreen = ({ navigation, route }) => {
// Screens where Bottom Tabs need to be hidden
const tabHiddenRoutes = [
"StartScreen",
"LoginScreen",
"SignupScreen",
"FindPropertyScreen",
"FindAddressManuallyScreen",
"PropertyDetailsScreen",
];
React.useLayoutEffect(() => {
const routeName = getFocusedRouteNameFromRoute(route);
if (tabHiddenRoutes.includes(getFocusedRouteNameFromRoute(route))) {
navigation.setOptions({ tabBarStyle: { display: "none" } });
} else {
navigation.setOptions({ tabBarStyle: { display: "flex" } });
}
}, [navigation, route]);
return (
<HomeStack.Navigator>
<HomeStack.Screen
name="StartScreen"
component={StartScreen}
options={{
title: "",
headerStyle: {
backgroundColor: "#0061FC",
},
headerTintColor: "#fff",
headerShadowVisible: false,
}}
/>
<HomeStack.Screen
name="LoginScreen"
component={LoginScreen}
options={{
title: "Login",
cardStyle: {
backgroundColor: "#fff",
},
}}
/>
<HomeStack.Screen
name="SignupScreen"
component={SignupScreen}
options={{
title: "Welcome",
cardStyle: {
backgroundColor: "#fff",
},
}}
/>
<HomeStack.Screen
name="FindPropertyScreen"
component={FindPropertyScreen}
options={{
title: "",
headerStyle: {
backgroundColor: "#0061FC",
},
headerTintColor: "#fff",
headerShadowVisible: false,
}}
/>
<HomeStack.Screen
name="FindAddressManuallyScreen"
component={FindAddressManuallyScreen}
options={{
title: "Enter address",
cardStyle: {
backgroundColor: "#fff",
},
}}
/>
<HomeStack.Screen
name="PropertyDetailsScreen"
component={PropertyDetailsScreen}
options={{
title: "Property Details",
cardStyle: {
backgroundColor: "#fff",
},
}}
/>
<HomeStack.Screen
name="DashboardScreen"
component={DashboardScreen}
options={{
title: "Your Dashboard",
cardStyle: {
backgroundColor: "#fff",
},
}}
/>
<HomeStack.Screen
name="TestScreen"
component={TestScreen}
options={{
title: "Test Screen",
cardStyle: {
backgroundColor: "#fff",
},
}}
/>
</HomeStack.Navigator>
);
};
const DashboardStack = createStackNavigator();
function DashboardStackScreen() {
return (
<DashboardStack.Navigator>
<DashboardStack.Screen
name="HomeReviewScreen"
component={HomeReviewScreen}
options={{
title: "",
cardStyle: {
backgroundColor: "#fff",
},
headerTintColor: "#fff",
headerShadowVisible: false,
}}
/>
</DashboardStack.Navigator>
);
}
const Tab = createBottomTabNavigator();
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
headerShown: false,
tabBarIcon: ({ focused, color, size }) => {
if (route.name === "Home") {
return (
<Ionicons
name={focused ? "home" : "home-outline"}
size={size}
color={color}
/>
);
} else if (route.name === "Dashboard") {
return (
<Ionicons
name={focused ? "settings" : "settings-outline"}
size={size}
color={color}
/>
);
} else if (route.name === "Finance") {
return (
<Ionicons
name={focused ? "card" : "card-outline"}
size={size}
color={color}
/>
);
} else if (route.name === "Contractor") {
return (
<Ionicons
name={focused ? "build" : "build-outline"}
size={size}
color={color}
/>
);
}
},
tabBarInactiveTintColor: "gray",
tabBarActiveTintColor: "#0061FC",
tabBarShowLabel: false,
})}
>
<Tab.Screen
name="Home"
component={HomeStackScreen}
// options={({ route }) => ({
// tabBarVisible: ((route) => {
// const routeName = getFocusedRouteNameFromRoute(route) ?? "";
// if (routeName === "StartScreen") {
// return false;
// }
// return true;
// })(route),
// })}
/>
<Tab.Screen
name="Contractor"
component={ContractorScreen}
options={{
title: "",
cardStyle: {
backgroundColor: "#fff",
},
}}
/>
<Tab.Screen name="Finance" component={FinanceScreen} />
<Tab.Screen name="Dashboard" component={DashboardStackScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
Have you try this rom react navigation doc :
The easiest way to achieve this is to nest the tab navigator inside
the first screen of the stack instead of nesting stack inside tab
navigator
I think the recommended way to do it is to set an id for your navigator
<Tab.Navigator ... id="NavID" />
and then use the navigator id
const tabNavigator = navigation.getParent('NavID')
tabNavigator.setOptions({ tabBarStyle: { display: "flex" } });

React Native Application Error - Couldn't find a 'component', 'getComponent' or 'children' prop for the screen 'Chat'

I tried to create a Chat screen but I am getting this error. I think I imported and exported everything correctly.
Error Message: Error: Couldn't find a 'component', 'getComponent' or 'children' prop for the screen 'Chat'. This can happen if you passed 'undefined'. You likely forgot to export your component from the file it's defined in, or mixed up default import and named import when importing.
This error is located at:
in StackNavigator (at App.js:60)
Chat.js :
import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
import {
firebase,
firebaseConfig,
db,
getUserDocument,
realtime,
} from "../../firebase/config";
import "firebase/auth";
import "firebase/firestore";
import "firebase/database";
const user = firebase.auth().currentUser;
export default class Chat extends React.Component {
static navigationOptions = {
title : 'Chat',
}
state = {
messages: [],
}
componentDidMount() {
this.setState({
messages: [
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
],
})
}
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
}
render() {
return (
<View style={{ flex: 1, backgroundColor: '#fff' }}>
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
user={{
_id: 1
}}
/>
</View>
)
}
}
App.js :
import 'react-native-gesture-handler';
import React, { Component, useEffect, useState } from 'react'
import { NavigationContainer, DefaultTheme } from '#react-navigation/native'
import {createAppContainer } from '#react-navigation/native'
import { createStackNavigator } from '#react-navigation/stack'
import { LoginScreen, HomeScreen, RegistrationScreen, Resource4, Screen1, Screen2, Screen3, Screen4, Page1, Page2, Page3, Page4, Chat } from './src/screens'
import { firebase } from './src/firebase/config'
// import { createTabNavigator } from 'react-navigation-tabs';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
function TabsStack() {
return (
<Tab.Navigator>
<Tab.Screen name='HomeScreen' component={HomeScreen} />
{/* <Tab.Screen name='Resource4' component={Resource4} /> */}
</Tab.Navigator>
)
}
const MyTheme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
primary: 'rgb(255, 45, 85)',
},
};
export default function App() {
const [loading, setLoading] = useState(true)
const [user, setUser] = useState(null)
const [loggedin, setLoggedIn] = useState(false)
useEffect(() => {
const usersRef = firebase.firestore().collection('users')
firebase.auth().onAuthStateChanged(user => {
if (user) {
usersRef
.doc(user.uid)
.get()
.then((document) => {
const userData = document.data()
setUser(userData)
setLoading(false)
})
.catch((error) => {
setLoading(false)
});
} else {
setLoading(false)
}
});
//return firebase.auth().onAuthStateChanged(setLoggedIn);
}, []);
return (
<NavigationContainer >
<Stack.Navigator initialRouteName={user ? 'Home' : 'Login'} >
<Stack.Screen name="HomeScreen" options={{ title: '', headerStyle: {
backgroundColor: '#caf7e3'
} }}>
{props => <HomeScreen {...props} extraData={user}/>}
</Stack.Screen>
<Stack.Screen name="Login" component={LoginScreen} options={{ title: 'Login', headerStyle: {
backgroundColor: '#caf7e3'
} }} />
<Stack.Screen name="Registration" component={RegistrationScreen} />
<Stack.Screen name="Resource4" component={Resource4} options={{ title: '', headerStyle: {
backgroundColor: '#caf7e3'
} }} />
<Stack.Screen name="Screen1" component={Screen1} options={{ title: '', headerStyle: {
backgroundColor: '#caf7e3'
} }}/>
<Stack.Screen name="Screen2" component={Screen2} options={{ title: 'COVID-19 & Pregnancy', headerStyle: {
backgroundColor: '#caf7e3'
} }}/>
<Stack.Screen name="Screen3" component={Screen3} />
<Stack.Screen name="Screen4" component={Screen4} />
<Stack.Screen name="Page1" component={Page1} options={{ title: '', headerStyle: {
backgroundColor: '#e4bad4'
} }} />
<Stack.Screen name="Page2" component={Page2} options={{ title: '', headerStyle: {
backgroundColor: '#a0829b'
} }} />
<Stack.Screen name="Page3" component={Page3} options={{ title: '', headerStyle: {
backgroundColor: '#e4bac2'
} }} />
<Stack.Screen name="Page4" component={Page4} options={{ title: '', headerStyle: {
backgroundColor: '#c197d2'
} }} />
<Stack.Screen name="Chat" component={Chat} options={{ title: '', headerStyle: {
backgroundColor: '#caf7e3'
} }} />
</Stack.Navigator>
</NavigationContainer>
);
}
//caf7e3
AppNavigator.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 HomeScreen from '.../HomeScreen/HomeScreen.js'
import Resource4 from '.../Resources/Resource4.js'
import LoginScreen from '.../LoginScreen/LoginScreen.js'
import Chat from '...Chat/Chat.js'
const Stack = createStackNavigator()
// const Tab = createBottomTabNavigator()
function getHeaderTitle(route) {
const routeName = route.state
? route.state.routes[route.state.index].name
: route.params?.screen || 'HomeScreen'
switch (routeName) {
case 'HomeScreen':
return 'HomesCreen'
case 'Resource4':
return 'Resource4'
case 'Chat':
return 'Chat'
}
}
function MainTabNavigator() {
return (
<Tab.Navigator
tabBarOptions={{
activeTintColor: '#101010',
style: {
backgroundColor: '#ffd700'
}
}}
screenOptions={({ route }) => ({
tabBarIcon: ({ color, size }) => {
let iconName
if (route.name == 'HomeScreen') {
iconName = 'ios-home'
} else if (route.name == 'Profile') {
iconName = 'ios-person'
}
return <Ionicons name={iconName} color={color} size={size} />
}
})}>
<Tab.Screen name='HomeScreen' component={HomeScreen} />
<Tab.Screen name='Resource4' component={Resource4} />
<Tab.Screen name='Chat' component={Chat} />
</Tab.Navigator>
)
}
function MainStackNavigator() {
return (
<NavigationContainer>
<Stack.Navigator screenOptions={{
headerShown: false
}} initialRouteName={user ? 'Home' : 'Login'}>
<Stack.Screen name="Home">
{props => <HomeScreen {...props} extraData={user} component={MainScreen}/>}
</Stack.Screen>
{/* <Stack.Screen name="Home" component={HomeScreen} /> */}
<Stack.Screen name="Login" component={LoginScreen} />
</Stack.Navigator>
</NavigationContainer>
)
}
'or mixed up default import and named import when importing.' this is your problem. Your Chat class is a default export, while you have imported it in App.js as otherwise. Change its import to:
import Chat from './src/screens'
and it should work. Though I'm also skeptical that ./src/screens is the correct location because in your AppNavigator you have it listed as
import Chat from '...Chat/Chat.js'

Import / Export error ? Couldn't find a 'component', 'getComponent' or 'children' prop

I need a little help, a fresh look at my code. I made a mistake but can't find where exactly.
I have the error:
Error: Couldn't find a 'component', 'getComponent' or 'children' prop
for the screen 'Les commandes'. This can happen if you passed
'undefined'. You likely forgot to export your component from the file
it's defined in, or mixed up default import and named import when
importing.
If I understood correctly the other posts which mention this problem, in general it is a syntax or import / export error, and here I must be too soaked with my code, I cannot see it. Could you read it again and give me a hand please?
Thank you so much.
App.js:
import React, { useState, useEffect } from 'react';
import AppContext from './AppContext';
import {NavigationContainer} from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import Authentication from './Screens/Authentication';
const AuthenticationStack = createStackNavigator();
import Splash from './src/components/Splash';
import BottomTabNavigator from './Navigation/TabNavigator';
export default function App() {
const [user, setUser] = useState({ loggedIn: false });
const state = { user, setUser };
const [loading, setLoading] = useState(true);
useEffect(() => {
setTimeout(() => setLoading(false), 2000);
}, []);
if (loading) {
return <Splash />;
}
return (
<AppContext.Provider value={state}>
<NavigationContainer>
{user.loggedIn ? (
<AuthenticationStack.Navigator>
<AuthenticationStack.Screen name="Authentication" component={Authentication} />
</AuthenticationStack.Navigator>
) : (
<BottomTabNavigator />
)}
</NavigationContainer>
</AppContext.Provider>
);
}
Bottomtabnavigator :
import React from "react";
import { Image } from 'react-native';
import Orders from '../Screens/Orders';
import Tools from '../Screens/Tools';
import Dashboard from '../Screens/Dashboard';
import { createBottomTabNavigator } from "#react-navigation/bottom-tabs";
import { MainStackNavigator, SettingsStackNavigator } from "./StackNavigator";
import styles from '../assets/styles';
import i18n from '../src/i18n';
const Tab = createBottomTabNavigator();
const BottomTabNavigator = () => {
return (
<Tab.Navigator tabBarOptions={{activeTintColor: 'black',
labelStyle: {fontSize: 12, color: 'white'},
style: {backgroundColor: '#F78400'},
}}>
<Tab.Screen
name={i18n.t("orders.title")}
component={MainStackNavigator}
options={{
tabBarIcon: ({ focused, horizontal, tintColor }) => {
return (
<Image
source={require("../assets/images/orders.png")}
style={styles.icon}
/>
);
}
}}
/>
<Tab.Screen
name={i18n.t("dashboard.title")}
component={Dashboard}
options={{
tabBarIcon: ({ focused, horizontal, tintColor }) => {
return (
<Image
source={require("../assets/images/dashboard.png")}
style={styles.icon}
/>
);
}
}}
/>
<Tab.Screen
name={i18n.t("tools.title")}
component={Tools}
options={{
tabBarIcon: ({ focused, horizontal, tintColor }) => {
return (
<Image
source={require("../assets/images/tools.png")}
style={styles.icon}
/>
);
}
}}
/>
<Tab.Screen
name={i18n.t("settings.title")}
component={SettingsStackNavigator}
options={{
tabBarIcon: ({ focused, horizontal, tintColor }) => {
return (
<Image
source={require("../assets/images/settings.png")}
style={styles.icon}
/>
);
}
}}
/>
</Tab.Navigator>
);
};
export default BottomTabNavigator;
StackNavigator :
import React from 'react';
import { createStackNavigator} from "#react-navigation/stack";
import Authentication from '../Screens/Authentication';
import Activities from '../Screens/Activities';
import Login from '../Screens/Login';
import Register from '../Screens/Register';
import Tools from '../Screens/Tools';
import Dashboard from '../Screens/Dashboard';
import Orders from '../Screens/Orders';
import About from '../Screens/About';
import Terms from '../Screens/Terms';
import Completed from '../Screens/Orders/Completed';
import Current from '../Screens/Orders/Current';
import Details from '../Screens/Orders/Details';
import Settings from '../Screens/Settings';
import Contact from '../Screens/Contact';
import Scan from '../Screens/Tools/Scan';
import Products from '../Screens/Tools/Products';
import Tickets from '../Screens/Tools/Tickets';
import Welcome from '../Screens/Welcome';
import i18n from '../src/i18n';
const Stack = createStackNavigator();
const screenOptionStyle = {
headerStyle: {
backgroundColor: "#F78400",
},
headerTintColor: "white",
headerBackTitle: "Back",
backgroundColor:'#f7f6f6'
};
const MainStackNavigator = () => {
return (
<Stack.Navigator screenOptions={screenOptionStyle}>
<Stack.Screen name = 'Orders' component = {Orders} options={{ title: i18n.t("orders.title") }}/>
<Stack.Screen name = 'Authentication' component = {Authentication} options={{ title: i18n.t("authentication.title") }}/>
<Stack.Screen name = 'Activities' component = {Activities} options={{ title: i18n.t("activities.title") }}/>
<Stack.Screen name = 'Contact' component = {Contact} options={{ title: i18n.t("contact.title") }}/>
<Stack.Screen name = 'Login' component = {Login} options={{ title: i18n.t("login.title") }}/>
<Stack.Screen name = 'Register' component = {Register} options={{ title: i18n.t("register.title") }}/>
<Stack.Screen name = 'Tools' component = {Tools} options={{ title: i18n.t("tools.title") }}/>
<Stack.Screen name = 'Scan' component = {Scan} options={{ title: i18n.t("scan.title") }}/>
<Stack.Screen name = 'Current' component = {Current} options={{ title: i18n.t("current.title") }}/>
<Stack.Screen name = 'Completed' component = {Completed} options={{ title: i18n.t("completed.title") }}/>
<Stack.Screen name = 'Details' component = {Details} options={{ title: i18n.t("details.title") }}/>
<Stack.Screen name = 'Products' component = {Products} options={{ title: i18n.t("products.title") }}/>
<Stack.Screen name = 'Terms' component = {Terms} options={{ title: i18n.t("terms.title") }}/>
<Stack.Screen name = 'About' component = {About} options={{ title: i18n.t("about.title") }}/>
<Stack.Screen name = 'Tickets' component = {Tickets} options={{ title: i18n.t("tickets.title") }}/>
<Stack.Screen name = 'Dashboard' component = {Dashboard} options={{ title: i18n.t("dashboard.title") }}/>
<Stack.Screen name = 'Settings' component = {Settings} options={{ title: i18n.t("settings.title") }}/>
<Stack.Screen name = 'Welcome' component = {Welcome} options={{ title: i18n.t("welcome.title") }}/>
</Stack.Navigator>
);
}
const SettingsStackNavigator = () => {
return (
<Stack.Navigator screenOptions={screenOptionStyle}>
<Stack.Screen name="Settings" component={Settings} />
</Stack.Navigator>
);
}
export default { MainStackNavigator, SettingsStackNavigator };
Orders :
import * as React from 'react';
import { Dimensions } from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
import Current from './Current'
import Completed from './Completed';
import styles from '../../assets/styles';
import i18n from '../../src/i18n';
const FirstRoute = () => (
<Current style={styles.scene} />
);
const SecondRoute = () => (
<Completed style={styles.scene} />
);
const initialLayout = { width: Dimensions.get('window').width };
export default function Orders() {
const [index, setIndex] = React.useState(0);
const [routes] = React.useState([
{ key: 'first', title: i18n.t("current.title") },
{ key: 'second', title: i18n.t("completed.title") },
]);
const renderScene = SceneMap({
first: FirstRoute,
second: SecondRoute,
});
return (
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>
);
}
As I followed the advice in comment I did :
console.log({ Orders, Authentication, Activities, Contact, Login,
Register, Tools, Scan, Current, Completed, Details, Products, Terms,
About, Tickets, Dashboard, Settings, Welcome });
It gives this:
Object {
"About": [Function About],
"Activities": [Function Activities],
"Authentication": [Function Authentication],
"Completed": [Function Completed],
"Contact": [Function Contact],
"Current": [Function Current],
"Dashboard": [Function Dashboard],
"Details": [Function Details],
"Login": [Function Login],
"Orders": [Function Orders],
"Products": [Function Products],
"Register": [Function Register],
"Scan": [Function Scan],
"Settings": [Function Settings],
"Terms": [Function Terms],
"Tickets": [Function Tickets],
"Tools": [Function Tools],
"Welcome": [Function App],
}

React navigation fail to navigate in APK build. But it works in Development Mode

I have trouble with my app.
My app has initial route to Home, then I want to navigate to other screen in HomeStackScreen eg. "Map" screen, then the app restart by itself.
The app works fine in development mode, but when it is build in the APK file, the navigation restart the app.
What I have tried,
navigation.navigate("Map") // fail in APK, but in development mode it works
navigation.navigate("Home",{screen:"Map"}) // fail in APK, but in development mode it works
navigation.jumpTo("Home",{screen:"Map"}) // fail in APK, but in development mode it works
navigation.push("Map") // fail in APK, but in development mode it works
navigation.replace("Map") // fail in APK, but in development mode it works
//
import React, { useState, useEffect, useRef } from "react";
import "react-native-gesture-handler";
import { NavigationContainer, useLinking } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import { createDrawerNavigator } from "#react-navigation/drawer";
//
import Home from "./Home";
import Map from "./Map";
import Testimoni from "./Testimoni";
import PasienHistory from "./PasienHistory";
import RiwayatPenyakit from "./RiwayatPenyakit";
import RequestTime from "./RequestTime";
import Waiting from "./Waiting";
import DoctorFound from "./DoctorFound";
import Welcome from "./Welcome";
import SignUp from "./SignUp";
import Login from "./Login";
import PasienBaru from "./PasienBaru";
import VerifyCode from "./VerifyCode";
import ListNakes from "./ListNakes";
import RequestStatus from "./RequestStatus";
import CustomRightHeader from "./CustomRightHeader";
import CustomLeftHeader from "./CustomLeftHeader";
import CustomHeaderBackHome from "./CustomHeaderBackHome";
import CustomHeaderBack from "./CustomHeaderBack";
import Loading from "./Loading";
import DrawerContent from "./DrawerContent";
import Profile from "./Profile";
import PatientListHistory from "./PatientListHistory";
import History from "./History";
import HistoryDetail from "./HistoryDetail";
import Transactions from "./Transactions";
import TransactionDetail from "./TransactionDetail";
import Support from "./Support";
//
import * as Permissions from "expo-permissions";
import * as Location from "expo-location";
//
import { Vibration, Platform, View, Text } from "react-native";
import * as Notifications from "expo-notifications";
import Constants from "expo-constants";
import * as Linking from "expo-linking";
//redux
import { useDispatch } from "react-redux";
import firebase from "./config/fbConfig";
//
import { LogBox } from "react-native";
const Drawer = createDrawerNavigator();
const HomeStack = createStackNavigator();
const AuthStack = createStackNavigator();
const ProfileStack = createStackNavigator();
const TransactionStack = createStackNavigator();
const PatientListHistoryStack = createStackNavigator();
const SupportStack = createStackNavigator();
LogBox.ignoreLogs(["Setting a timer"]);
const Index = () => {
const dispatch = useDispatch();
const [uid, setUid] = useState(false);
//expo-linking
const ref = useRef(null);
const [isReady, setIsReady] = useState(false);
const [initialState, setInitialState] = useState();
const prefix = Linking.makeUrl("/");
const linkingTo = (path) => {
const redirectUrl = Linking.makeUrl(path);
return Linking.openURL(redirectUrl);
};
const { getInitialState } = useLinking(ref, {
prefixes: [prefix],
});
//
const checkLocationPermissionAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status === "granted") {
await Location.hasServicesEnabledAsync().then(async (service) => {
if (service) {
return true;
} else {
alert("Lokasi tidak aktif");
return false;
}
});
} else {
alert("Ijin lokasi tidak aktif");
return false;
}
};
const checkForPushNotificationsAsync = async () => {
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Permissions.askAsync(
Permissions.NOTIFICATIONS
);
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Ijin notifikasi tidak aktif!");
return;
}
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
};
const handleNotification = async (notification) => {
Vibration.vibrate();
let { identifier } = await notification.request;
await dispatch({ type: "NOTIFICATION", notification });
await linkingTo("RequestStatus");
setTimeout(() => Notifications.dismissNotificationAsync(identifier), 300);
};
const handleOnClickNotification = async (response) => {
let { notification } = response;
Vibration.vibrate();
await dispatch({ type: "NOTIFICATION", notification });
await linkingTo("RequestStatus");
};
const onClickNotification = async () => {
await Notifications.addNotificationResponseReceivedListener(
handleOnClickNotification
);
};
const listenNotification = async () => {
await Notifications.addNotificationReceivedListener(handleNotification);
};
//
const onLoad = async () => {
//expo-linking
await getInitialState()
.catch(() => {})
.then((state) => {
if (state !== undefined) {
setInitialState(state);
}
setIsReady(true);
});
firebase.auth().onAuthStateChanged((user) => {
if (user) {
user.getIdTokenResult().then((idTokenResult) => {
if (idTokenResult.claims.patient) {
setUid(user.uid);
checkLocationPermissionAsync();
checkForPushNotificationsAsync();
listenNotification();
onClickNotification();
dispatch({ type: "OFF_LOADING" });
} else {
setUid(false);
dispatch({ type: "OFF_LOADING" });
}
});
} else {
setUid(false);
dispatch({ type: "OFF_LOADING" });
}
});
};
useEffect(() => {
onLoad();
// return () => {
// setUid(false);
// };
}, [getInitialState, uid]);
const HomeStackScreen = () => (
<HomeStack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: "#29ACE3",
},
headerMode: "float",
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold",
color: "#fff",
fontSize: 14,
},
headerTitleAlign: "center",
headerBackTitleVisible: false,
headerStatusBarHeight: 20,
}}
>
<HomeStack.Screen
name="Home"
component={Home}
options={({ navigation }) => ({
title: "HOMECARE",
headerLeft: () => <CustomLeftHeader navigation={navigation} />,
headerRight: () => <CustomRightHeader />,
})}
/>
<HomeStack.Screen
name="Map"
component={Map}
options={({ navigation }) => ({
title: "Tentukan Lokasi Pasien",
})}
/>
<HomeStack.Screen
name="PasienHistory"
component={PasienHistory}
options={({ navigation }) => ({
title: "Pilih Pasien",
})}
/>
<HomeStack.Screen
name="PasienBaru"
component={PasienBaru}
options={({ navigation }) => ({
title: "Pasien Baru",
})}
/>
<HomeStack.Screen
name="RiwayatPenyakit"
component={RiwayatPenyakit}
options={({ navigation }) => ({
title: "Riwayat Penyakit",
})}
/>
<HomeStack.Screen
name="RequestTime"
component={RequestTime}
options={({ navigation }) => ({
title: `Waktu Kunjungan`,
headerLeft: () => <CustomHeaderBackHome navigation={navigation} />,
})}
/>
<HomeStack.Screen
name="ListNakes"
component={ListNakes}
options={({ navigation }) => ({
title: `Pilih Petugas`,
headerLeft: () => (
<CustomHeaderBack navigation={navigation} path={"RequestTime"} />
),
})}
/>
<HomeStack.Screen
name="DoctorFound"
component={DoctorFound}
options={({ navigation }) => ({
title: `Petugas Ditemukan`,
headerLeft: null,
})}
/>
<HomeStack.Screen
name="Waiting"
component={Waiting}
options={({ navigation }) => ({
headerLeft: null,
})}
/>
<HomeStack.Screen
name="RequestStatus"
component={RequestStatus}
options={({ navigation }) => ({
title: `Permintaan Berhasil`,
headerLeft: () => <CustomHeaderBackHome navigation={navigation} />,
})}
/>
</HomeStack.Navigator>
);
const AuthStackScreen = () => (
<AuthStack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: "#29ACE3",
},
headerMode: "float",
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold",
color: "#fff",
fontSize: 14,
},
headerTitleAlign: "center",
headerBackTitleVisible: false,
headerStatusBarHeight: 20,
}}
>
<AuthStack.Screen name="Welcome" component={Welcome} />
<AuthStack.Screen
name="SignUp"
component={SignUp}
options={({ navigation }) => ({
title: `Registrasi`,
})}
/>
<AuthStack.Screen name="Login" component={Login} />
<AuthStack.Screen
name="VerifyCode"
component={VerifyCode}
options={({ navigation }) => ({
title: `Verifikasi Kode`,
})}
/>
</AuthStack.Navigator>
);
const TransactionStackScreen = () => (
<TransactionStack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: "#29ACE3",
},
headerMode: "float",
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold",
color: "#fff",
fontSize: 14,
},
headerTitleAlign: "center",
headerBackTitleVisible: false,
headerStatusBarHeight: 20,
}}
>
<TransactionStack.Screen
name="Transactions"
component={Transactions}
options={({ navigation }) => ({
title: `Transaksi`,
headerLeft: () => <CustomLeftHeader navigation={navigation} />,
})}
/>
<TransactionStack.Screen
name="TransactionDetail"
component={TransactionDetail}
options={({ navigation }) => ({
title: `Detail Transaksi`,
})}
/>
</TransactionStack.Navigator>
);
const PatientListHistoryStackScreen = () => (
<PatientListHistoryStack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: "#29ACE3",
},
headerMode: "float",
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold",
color: "#fff",
fontSize: 14,
},
headerTitleAlign: "center",
headerBackTitleVisible: false,
headerStatusBarHeight: 20,
}}
>
<PatientListHistoryStack.Screen
name="PatientListHistory"
component={PatientListHistory}
options={({ navigation }) => ({
title: `Pilih Pasien`,
headerLeft: () => <CustomLeftHeader navigation={navigation} />,
})}
/>
<PatientListHistoryStack.Screen name="History" component={History} />
<PatientListHistoryStack.Screen
name="HistoryDetail"
component={HistoryDetail}
options={({ navigation }) => ({
title: `Detail History`,
})}
/>
</PatientListHistoryStack.Navigator>
);
const ProfileStackScreen = () => (
<ProfileStack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: "#29ACE3",
},
headerMode: "float",
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold",
color: "#fff",
fontSize: 14,
},
headerTitleAlign: "center",
headerBackTitleVisible: false,
headerStatusBarHeight: 20,
}}
>
<ProfileStack.Screen
name="Profile"
component={Profile}
options={({ navigation }) => ({
headerLeft: () => <CustomLeftHeader navigation={navigation} />,
})}
/>
</ProfileStack.Navigator>
);
const SupportStackScreen = () => (
<SupportStack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: "#29ACE3",
},
headerMode: "float",
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold",
color: "#fff",
fontSize: 14,
},
headerTitleAlign: "center",
headerBackTitleVisible: false,
headerStatusBarHeight: 20,
}}
>
<SupportStack.Screen
name="Support"
component={Support}
options={({ navigation }) => ({
headerLeft: () => <CustomLeftHeader navigation={navigation} />,
})}
/>
</SupportStack.Navigator>
);
if (!isReady) {
return null;
}
return (
<NavigationContainer
initialState={initialState}
ref={ref}
fallback={<Loading loading={true} />}
>
{uid ? (
<Drawer.Navigator
initialRouteName="Home"
drawerContent={(props) => <DrawerContent {...props} />}
>
<Drawer.Screen name="Home" component={HomeStackScreen} />
<Drawer.Screen name="Profile" component={ProfileStackScreen} />
<Drawer.Screen
name="Transactions"
component={TransactionStackScreen}
/>
<Drawer.Screen
name="PatientListHistory"
component={PatientListHistoryStackScreen}
/>
<Drawer.Screen name="Support" component={SupportStackScreen} />
</Drawer.Navigator>
) : (
<AuthStackScreen />
)}
</NavigationContainer>
);
};
export default Index;
I am sorry, I already has the answer.
The problem is not in react navigation but in react-native-maps.