React navigation 5 ( navigate to another stack Screen) - react-native

this is my appNavigator: I divide into 3 stackScreen include HomeStack, SettingsStack and ProfileStack. AuthStack contain SignUp and Signin Screen, and i create bottom tab contain 3 StackScreen above
const HomeStack = createStackNavigator();
function HomeStackScreen() {
return (
<HomeStack.Navigator headerMode="none">
<HomeStack.Screen name="Home" component={HomeScreen} />
<HomeStack.Screen name="Details" component={DetailsScreen} />
</HomeStack.Navigator>
);
}
const SettingsStack = createStackNavigator();
function SettingsStackScreen() {
return (
<SettingsStack.Navigator>
<SettingsStack.Screen name="Settings" component={SettingsScreen} />
<SettingsStack.Screen name="Details" component={DetailsScreen} />
</SettingsStack.Navigator>
);
}
const ProfileStack = createStackNavigator();
function ProfileStackScreen({navigation}) {
return (
<ProfileStack.Navigator>
<ProfileStack.Screen name="Profile" component={ProfileScreen} />
</ProfileStack.Navigator>
);
}
// ** AUTH ** //
const AuthStack = createStackNavigator();
function AuthStackScreen() {
return (
<AuthStack.Navigator headerMode="none">
<AuthStack.Screen name="SignIn" component={LoginScreen} />
<AuthStack.Screen name="SignUp" component={SignUpScreen} />
</AuthStack.Navigator>
);
}
// ** APP ** //
const AppStack = createBottomTabNavigator();
function AppStackScreen() {
return (
<AppStack.Navigator name="mainApp">
<AppStack.Screen name="Dashboard" component={HomeStackScreen} />
<AppStack.Screen name="Favorite" component={SettingsStackScreen} />
<AppStack.Screen name="Profile" component={ProfileStackScreen} />
</AppStack.Navigator>
);
}
// ** ROOT ** //
const RootStack = createStackNavigator();
const RootStackScreen = ({userToken}) => {
return (
<RootStack.Navigator headerMode="none">
<RootStack.Screen name="Auth" component={AuthStackScreen} />
<RootStack.Screen name="App" component={AppStackScreen} />
</RootStack.Navigator>
);
};
export default function AppNavigator() {
const [loading, setloading] = React.useState(true);
const [userToken, setUserToken] = React.useState();
React.useEffect(() => {
setTimeout(() => {
setloading(false);
}, 1000);
});
if (loading) {
return <SplashScreen />;
}
// })
return (
<NavigationContainer>
<RootStackScreen />
</NavigationContainer>
);
}
and this is my Login Screen :
const LoginScreen = ({ navigation, props }) => {
console.tron.log("debug: LoginScreen -> props", props, navigation)
const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState('');
const [error, setError] = React.useState('');
const [loading, setLoading] =React.useState(false)
const handleLogin = () => {
if (email === '' && password === '') {
Alert.alert('Enter details to signin!')
} else {
setLoading(true)
firebase
.auth()
.signInWithEmailAndPassword(email,password)
.then((res) => {
console.log(res)
console.log('User logged-in successfully!')
setLoading(false)
setEmail('')
setPassword('')
navigation.navigate("AppStack", {screen: "Dashboard"})
})
.catch(error => setError(error.message))
}
}
return (
<ImageBackground source={require('../images/background.jpg')} style={styles.imageBack}>
<View style={styles.area1}>
<Image
source={require('../images/vaccines.png')}
style={styles.logo} />
<View style={styles.box}>
<TextInput
placeholder='Email'
onChangeText={email => setEmail(email)}
value={email}
maxLength={15}
/>
</View>
<View style={styles.box}>
<TextInput
placeholder='Password'
secureTextEntry={true}
onChangeText={password => setPassword(password)}
value={password}
maxLength={15}
/>
</View>
<BlockIcon />
<TouchableOpacity style={styles.buttonLogin} onPress={handleLogin}>
<Text style={styles.text1}>Sign In</Text>
</TouchableOpacity>
<View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 50 }}>
<Text style={styles.text2}> If you don't have an account ?</Text>
<TouchableOpacity onPress={() => navigation.push('SignUp')}>
<Text style={styles.text3}> Sign Up </Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
)
}
I navigate at navigation.navigate("AppStack", {screen: "Dashboard"})
when I login successful. I want to navigate to AppStack (bottomtab with initial Screen name is Dasboard) I try to use nesting navigator but unsuccessful. I also try to use navigation.navigate('HomeScreen'), but it not work. Anyone can help me =((. Thanks

I know this is a month old but maybe this will help someone else.
Looks like you're close. In your RootStackScreen, you have two screens: "Auth" and "App". And it sounds like you want to go to your "App" screen from your "Auth" screen. You just need to use the name of the screen.
navigation.navigate("App", {screen: "Dashboard"})

Related

route.params not returning a variable with React Navigation

I'm attempting to pass a variable from one screen to another using React Navigation's route.params.
I've got this working on the screen immediately preceding it, but it's failing on the next screen and I cannot figure out why.
Here's the code:
setTimeout(() => {
console.log('here is the hid: ' + results.data.hid);
navigation.navigate('MainHome', {
hid: results.data.hid,
});
}, 2500);
The console log is correctly displaying the correct data in the console. This code leads to the next screen:
function Home({route, navigation}) {
const hid = route.params;
const [results, setResults] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const [loading, setLoading] = useState('loading');
console.log('Here is the hid that is retrieved from the route params on home:' + hid);
This console log is showing the hid as undefined.
Here is the expanded code for the referring screen:
function IntroOne({route, navigation}) {
const [results, setResults] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const [loading, setLoading] = useState('loading');
const {email, password} = route.params;
const CPRAPI = () => {
api
.get('create_account.php', {
params: {
email: email,
password: password,
},
})
.then(function (response) {
// handle success
setResults(response);
setLoading('success');
})
.catch(function (error) {
// handle error
console.log('ERROR :(');
console.log(error);
setErrorMessage(error);
});
};
useEffect(() => {
CPRAPI();
}, []);
if (loading != 'success') {
return (
<View style={styles.container}>
<Image
style={{width: windowWidth, maxHeight: 250}}
source={require('../components/parallel_universe.jpg')}
/>
<ActivityIndicator size={'large'} color={'#ee1c24'} />
<Text style={styles.header}>Loading...</Text>
</View>
);
} else {
if (results.data.intro_complete == 1) {
setTimeout(() => {
console.log('here is the hid: ' + results.data.hid);
navigation.navigate('MainHome', {
hid: results.data.hid,
});
}, 2500);
return (
<View style={styles.container}>
<Image
style={{width: windowWidth, maxHeight: 250}}
source={require('../components/parallel_universe.jpg')}
/>
<ActivityIndicator size={'large'} color={'#ee1c24'} />
<Text style={styles.header}>Almost Done...</Text>
</View>
);
}
Here is the expanded code for the receiving page:
function Home({route, navigation}) {
const hid = route.params.hid;
const [results, setResults] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const [loading, setLoading] = useState('loading');
console.log('Here is the hid that is retrieved from the route params on home:' + hid);
const CPRAPI = () => {
api
.get('home.php', {
params: {
hid: hid,
},
})
.then(function (response) {
// handle success
setResults(response);
setLoading('success');
})
.catch(function (error) {
// handle error
console.log('ERROR :(');
console.log(error);
setErrorMessage(error);
});
};
useEffect(() => {
CPRAPI();
}, []);
if (loading == 'loading') {
return (
<View style={styles.container}>
<Image
style={{width: windowWidth, maxHeight: 250}}
source={require('../components/parallel_universe.jpg')}
/>
<ActivityIndicator size={'large'} color={'#ee1c24'} />
<Text style={styles.header}>Loading...</Text>
</View>
);
} else {
return (
<View>
<Header
placement="center"
leftComponent={
<View>
<FontAwesomeIcon
style={{margin: 9}}
icon={['far', 'badge-dollar']}
/>
<Text>{results.data.home_screen[0].firstname}</Text>
</View>
}
centerComponent={{text: 'Hello, ', style: {color: '#fff'}}}
rightComponent={
<FontAwesomeIcon
style={{margin: 9}}
icon={['far', 'question-circle']}
/>
}
/>
<ScrollView>
<View style={styles.container}>
<Image
style={{width: windowWidth, maxHeight: windowHeight / 5}}
source={require('../components/parallel_universe.jpg')}
/>
<Text style={styles.header}>Hello, {}</Text>
<Text style={styles.textSmaller} />
<Text style={styles.textMuchSmaller}>
We will never spam you or sell your email.
</Text>
</View>
</ScrollView>
</View>
);
}
}
Here are my stacks:
const GettingStartedStack = createStackNavigator();
function GettingStartedScreen() {
return (
<GettingStartedStack.Navigator>
<GettingStartedStack.Screen
name="Getting Started"
component={GettingStarted}
options={{headerShown: false}}
/>
<GettingStartedStack.Screen
name="Question One"
component={gs1}
options={{title: 'Your Shadow Self'}}
/>
<GettingStartedStack.Screen
name="Defining Moment Narrative"
component={gs1entry}
/>
<GettingStartedStack.Screen
name="Question Two"
component={gs2}
options={{title: 'Credits & Money'}}
/>
<GettingStartedStack.Screen
name="Define Myself"
component={gs2entry}
options={{title: 'College'}}
/>
<GettingStartedStack.Screen
name="Concentration"
component={gs2Aentry}
options={{title: 'Concentration'}}
/>
<GettingStartedStack.Screen
name="Homeland"
component={gs3}
options={{title: 'Your Homeland'}}
/>
<GettingStartedStack.Screen
name="Choose Homeland"
component={gs3entry}
options={{title: 'Choose Your Homeland'}}
/>
<GettingStartedStack.Screen
name="Citizenship"
component={gs4}
options={{title: 'Your Citizenship'}}
/>
<GettingStartedStack.Screen
name="Choose Citizenship"
component={gs4entry}
options={{title: 'Choose Your Citizenship'}}
/>
<GettingStartedStack.Screen name="Banking" component={gs5} />
<GettingStartedStack.Screen
name="Choose Banking"
component={gs5entry}
options={{title: 'Choose Your Bank'}}
/>
<GettingStartedStack.Screen
name="Luck"
component={gs6}
options={{title: 'Are You Feeling Lucky?'}}
/>
<GettingStartedStack.Screen name="Parents" component={gs7} />
<GettingStartedStack.Screen name="Siblings" component={gs8} />
<GettingStartedStack.Screen name="Inheritance" component={gs9} />
<GettingStartedStack.Screen name="More Credits" component={moreCredits} />
</GettingStartedStack.Navigator>
);
}
const IntroStack = createStackNavigator();
function IntroStackScreen() {
return (
<IntroStack.Navigator>
<IntroStack.Screen
name="Welcome"
component={IntroOne}
options={{headerShown: false}}
/>
<IntroStack.Screen
name="Empire Universe"
component={IntroTwo}
options={{headerShown: false}}
/>
<IntroStack.Screen
name="Shadow Self"
component={IntroThree}
options={{headerShown: false}}
/>
</IntroStack.Navigator>
);
}
const HomeStack = createStackNavigator();
function HomeStackScreen() {
return (
<HomeStack.Navigator>
<HomeStack.Screen
name="Home"
component={Home}
options={{headerShown: false}}
/>
</HomeStack.Navigator>
);
}
const FinancesStack = createStackNavigator();
function FinancesStackScreen() {
return (
<FinancesStack.Navigator>
<FinancesStack.Screen
name="Finances"
component={Finances}
options={{headerShown: false}}
/>
</FinancesStack.Navigator>
);
}
const Tab = createBottomTabNavigator();
function MainTabs() {
return (
<Tab.Navigator
screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
let iconName;
if (route.name === 'Cyclopedia') {
iconName = focused ? 'books' : 'books';
} else if (route.name === 'Big Think') {
iconName = focused ? 'head-side-brain' : 'head-side-brain';
} else if (route.name === 'Getting Started') {
iconName = focused ? 'key-skeleton' : 'key-skeleton';
} else if (route.name === 'CSX') {
iconName = focused ? 'chart-area' : 'chart-area';
} else if (route.name === 'Marketwire') {
iconName = focused ? 'analytics' : 'analytics';
} else if (route.name === 'Login') {
iconName = focused ? 'user-cog' : 'user-cog';
} else if (route.name === 'Map') {
iconName = focused ? 'map' : 'map';
} else if (route.name === 'Intro') {
iconName = focused ? 'home' : 'home';
} else {
iconName = focused ? 'books' : 'books';
}
// You can return any component that you like here!
return <FontAwesomeIcon icon={['far', iconName]} />;
},
})}
tabBarOptions={{
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
}}>
<Tab.Screen name="Home" component={HomeStackScreen} />
<Tab.Screen name="Finances" component={FinancesStackScreen} />
</Tab.Navigator>
);
}
const MainStack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<MainStack.Navigator>
<MainStack.Screen
name="Welcome"
component={IntroStackScreen}
options={{headerShown: false}}
/>
<MainStack.Screen
name="MainHome"
component={MainTabs}
options={{headerShown: false}}
/>
<MainStack.Screen
name="Getting Started"
component={GettingStartedScreen}
options={{headerShown: false}}
/>
</MainStack.Navigator>
</NavigationContainer>
);
}
Any thoughts about what could be causing this? I've tried a bunch of things, but just can't seem to get it to resolve properly.
I'm using:
React Native - 0.63.4
"#react-navigation/bottom-tabs": "^5.11.7",
"#react-navigation/native": "^5.9.2",
"#react-navigation/stack": "^5.14.1",
Thanks in advance!
In react-navigation 5 ... we need to specify what screen you wanna navigate to in case of nested-navigators...
Try this:
navigate('MainHome', {
screen: Home,
params: {
screen: 'Home',
params: {
hid: results.data.hid,
},
},
});
This will work.
function Home({route, navigation}) {
const hid = route.params.hid;
const [results, setResults] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const [loading, setLoading] = useState('loading');
console.log('Here is the hid that is retrieved from the route params on home:' + hid);

react native - What should I do each time <textinput> is input, so <Google> in </NavigationContainer> cannot be re-rendered?

App.tsx
const Tab = createMaterialTopTabNavigator();
export default function App() {
const [text, setText] = useState('');
const [search, setSearch] = useState('');
const searchHandler = () => {
setSearch(text)
}
return (
<NavigationContainer>
<View style={styles.case1}></View>
<View style={styles.case1}>
<TextInput
style={styles.input}
placeholder='search'
onChangeText={(val) => setText(val)}
/>
<Button
onPress={searchHandler}
title="search button"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</View>
<Tab.Navigator>
<Tab.Screen name="google1" component={() => <Google item={search} />} />
<Tab.Screen name="google2" component={() => <Google2 item={search} />} />
</Tab.Navigator>
</NavigationContainer>
);
}
Google.tsx
export default function google(props) {
return (
<View style={styles.webContainer}>
<WebView
source={{
uri:
'https://www.google.com/search?hl=en&sxsrf=ALeKk03BNJhsVEURZyXdlkOpk1l1qb2Nug%3A1595674787434&source=hp&ei=oxAcX4qzGLLxhwOhw5jwBA&q=' + props.item + '&oq=' +** props.item ** +'&gs_lcp=CgZwc3ktYWIQAzIFCC4QkwIyAggAMgIIADICCC4yAggAMgIIADICCAAyAggAMgIIADICCAA6BAgjECc6BQguEJECOgUIABCRAjoICC4QxwEQowI6BwguEEMQkwI6CAguEMcBEK8BUPEDWOkHYKwIaABwAHgAgAGMAYgBigOSAQMwLjOYAQCgAQGqAQdnd3Mtd2l6&sclient=psy-ab&ved=0ahUKEwjKkIXnn-jqAhWy-GEKHaEhBk4Q4dUDCAc&uact=5'
}}
/>
</View>
);
};
I'm creating an app that searches across different sites by typing in the search bar.
Whenever I type in the web-view keeps re-rendering. I only want to be re-rendered(Google web-view) when I click the search button.
I've heard that should use use-memo, Callback, as far as I know.
Thanks
const searchHandler = () => {
setSearch(text) <- "text" is a reference
}
try
const searchHandler = () => {
setSearch(`${text}`)
}
Prevent rerender WebView from props through useMemo. (memoization)
export default function google(props) {
const Web = React.useMemo(() => {
return <WebView source={{uri: 'abc'}} />
}, [])
return (
<View style={styles.webContainer}>
{Web}
</View>
);
};

React Native Context, how to share context beetwing multiple nested files and components

I'm quiete new to react native, and im stuck on passing context between components in different files
basically im building login flow following the react navigation auth-flow https://reactnavigation.org/docs/auth-flow/
my scenario looks as follow:
in App.js
a stack screen with Login/Register/Home, showing Login/Register or Home based on login status
the Home Screen is made by a component which is a drawer, using a custom drawer and two component (Home and About)
//VARIOUS IMPORT
const Drawer = createDrawerNavigator();
const HeaderOption = () => ({
headerShown: false,
// animationTypeForReplace: state.isSignout ? 'pop' : 'push',
});
const AppStack = createStackNavigator();
const AuthContext = createContext();
//THE DRAWER FOR HOME
function DrawerNavigator(props) {
return (
<Drawer.Navigator
initialRouteName="Home"
drawerContent={(props) => MyDrawer(props)}
>
<Drawer.Screen name="Home" component={Home} />
<Drawer.Screen name="About" component={About} />
</Drawer.Navigator>
);
}
//MAIN APP
export default function App({ navigation }) {
const [state, dispatch] = useReducer(
(prevState, action) => {
switch (action.type) {
case 'RESTORE_TOKEN':
return {
...prevState,
userToken: action.token,
isLoading: false,
};
case 'SIGN_IN':
return {
...prevState,
isSignout: false,
userToken: action.token,
};
case 'SIGN_OUT':
return {
...prevState,
isSignout: true,
userToken: null,
};
}
},
{
isLoading: true,
isSignout: false,
userToken: null,
}
);
useEffect(() => {
// Fetch the token from storage then navigate to our appropriate place
const bootstrapAsync = async () => {
let userToken;
try {
userToken = await AsyncStorage.getItem('userToken');
} catch (e) {
}
dispatch({ type: 'RESTORE_TOKEN', token: userToken });
};
bootstrapAsync();
}, []);
const authContext = useMemo(
() => ({
signIn: async (data) => {
// LOGIN PROCEDURE
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
signOut: () => dispatch({ type: 'SIGN_OUT' }),
signUp: async (data) => {
// SUBSCRIBE PROCEDURE
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
}),
[]
);
if (state.isLoading) {
// We haven't finished checking for the token yet
return (
<View>
<Text>Loading</Text>
</View>
);
}
return (
<AuthContext.Provider value={authContext}>
<NavigationContainer>
<AppStack.Navigator initialRouteName="Login">
{state.userToken == null ? (
<>
<AppStack.Screen
name="Login"
component={LoginScreen}
options={HeaderOption}
/>
<AppStack.Screen
name="Register"
component={RegisterScreen}
options={HeaderOption}
/>
</>
) : (
<AppStack.Screen
name="HomeApp"
component={DrawerNavigator}
options={HeaderOption}
/>
)}
</AppStack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
);
}
in LoginScreen.js
the effective login screen (which is showed at app startup if not logged in)
//import
export default function LoginScreen(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const { signIn } = useContext(AuthContext);
return (
<View
style={{
flex: 1,
backgroundColor: Constants.MAIN_GREEN,
}}
>
<View style={{ ...styles.container }}>
<StatusBar hidden={true} />
<View style={{ ...styles.logoContainer }}>
<Image
style={styles.logoIcon}
source={require('../assets/logo_popeating_amp.png')}
/>
</View>
<View style={{ ...styles.inputContainer }}>
<Image
style={styles.inputIcon}
source={require('../assets/mail.png')}
/>
<TextInput
autoFocus={true}
placeholder="Email address"
onChangeText={(email) => setEmail(email)}
value={email}
label="Email"
style={styles.inputs}
keyboardType={'email-address'}
/>
</View>
<View style={{ ...styles.inputContainer }}>
<Image
style={styles.inputIcon}
source={require('../assets/password.png')}
/>
<TextInput
placeholder="Password"
onChangeText={(password) => setPassword(password)}
value={password}
secureTextEntry={true}
label="Password"
style={styles.inputs}
/>
</View>
<TouchableHighlight
style={[styles.buttonContainer, styles.loginButton]}
onPress={() => signIn({ email, password })}
underlayColor={Constants.HI_COLOR}
>
<Text style={styles.loginText}>LOGIN</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonContainer}
onPress={() => props.navigation.navigate('HomeApp')}
underlayColor={Constants.HI_COLOR}
>
<Text>Forgot your password?</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonContainer}
onPress={() => props.navigation.navigate('Register')}
underlayColor={Constants.HI_COLOR}
>
<Text>Register</Text>
</TouchableHighlight>
</View>
</View>
);
}
const styles = StyleSheet.create({
//styles
});
in DrawerContent.js
the drawer for the home which contain a link to Home, a link to About, a link to Logout
in Home.js
the main page which is the initialroute of the Drawer
every time i try to start the app
the error is
Unhandled promise rejection: ReferenceError: Can't find variable: AuthContext
it seems LoginScreen cant access AuthContext, how can i have AuthContext available to other components between files?
You can place the context creation in a separate file
//AuthContext.js
const AuthContext = createContext();
export default AuthContext;
In app.js you can simply import this and use this
import AuthContext from './AuthContext.js';
You can do the same for login.js as well
Then it will work as expected.

React Navigation 5.x Drawer Issue

Getting the following Issue when I use Drawer. Stack and Tab are working fine without Drawer.
Does anyone know what is going on here and can help me?
enter image description here
Here is Navigator File some Code lines:
const Stack = createStackNavigator();
const FavStack = createStackNavigator();
const FilterStack = createStackNavigator();
const Tab =
Platform.OS === "android"
? createMaterialBottomTabNavigator()
: createBottomTabNavigator();
const defaultScreenOptions = {
headerStyle: { backgroundColor: colors.primary },
headerTintColor: "white",
};
function MealsNavigator() {
return (
<Stack.Navigator screenOptions={defaultScreenOptions}>
<Stack.Screen name="Meals Categories" component={CategoriesScreen} />
<Stack.Screen name="Profile" component={CategoryMealScreen} />
<Stack.Screen name="Details" component={MealDetailsScreen} />
</Stack.Navigator>
);
}
function FavStackNavigator() {
return (
<FavStack.Navigator screenOptions={defaultScreenOptions}>
<FavStack.Screen name="Favourites" component={FavouritesScreen} />
<FavStack.Screen name="Details" component={MealDetailsScreen} />
</FavStack.Navigator>
);
}
function MealsFavTabNavigator() {
return (
<Tab.Navigator
tabBarOptions={{ activeTintColor: colors.accent }}
shifting={true}
>
<Tab.Screen
name="All"
component={MealsNavigator}
options={{
tabBarLabel: "Meals",
tabBarIcon: (tabInfo) => (
<Ionicons name="ios-restaurant" size={25} color={tabInfo.color} />
),
tabBarColor: colors.primary,
}}
/>
<Tab.Screen
name="Favourites"
component={FavStackNavigator}
options={{
tabBarIcon: (tabInfo) => (
<Ionicons name="ios-star" size={25} color={tabInfo.color} />
),
tabBarColor: colors.accent,
}}
/>
</Tab.Navigator>
);
}
function FilterStackNavigator() {
return (
<FilterStack.Navigator>
<FilterStack.Screen name="Filters" component={FilterScreen} />
</FilterStack.Navigator>
);
}
const Drawer = createDrawerNavigator();
function MenuNavigator() {
return (
<Drawer.Navigator>
<Drawer.Screen name="MealFavs" component={MealsFavTabNavigator} />
<Drawer.Screen name="Filters" component={FilterStackNavigator} />
</Drawer.Navigator>
);
}
export default MenuNavigator;
Here is App.js few Code lines:
export default function App() {
const [fontLoaded, setFontLoaded] = useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => setFontLoaded(true)}
onError={(err) => console.log(err)}
/>
);
}
return <NavigationContainer><MealsNavigator /></NavigationContainer>
}
Code is not giving error without Drawer, It is working exactly fine with Stack and Tab Navigators!

How to call toggleDrawer in React Navigation 5

I got a React-Navigation 5 drawer menu working using gesture, but I also want to add an icon on the right side of the header to toggle the drawer menu.
I have the navigation setup in my App.js like this:
import {NavigationContainer, DrawerActions} from '#react-navigation/native';
//....... other imports
const HomeStack = createStackNavigator();
const HomeStackScreens = () => (
<HomeStack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: '#5C6BC0',
},
headerTintColor: '#fff',
headerRight: () => {
return (
<TouchableOpacity
onPress={() => DrawerActions.toggleDrawer()}>
<Icon name="bars" color="#FFF" size={18} />
</TouchableOpacity>
);
},
}}>
<HomeStack.Screen
name="Home"
component={HomeScreen}
options={{
header:({scene, previous, navigation}) => {
return (
<TouchableOpacity onPress={() => navigation.toggleDrawer()}>
<Icon name="bars" color="#FFF" size={18} />
</TouchableOpacity>
);
}
}}
/>
<HomeStack.Screen name="Login" component={Login} />
<HomeStack.Screen name="Register" component={Register} />
</HomeStack.Navigator>
);
const ProfileStack = createStackNavigator();
const ProfileStackScreens = () => (
<ProfileStack.Navigator>
<ProfileStack.Screen name="Profile" component={Profile} />
</ProfileStack.Navigator>
);
const SettingStack = createStackNavigator();
const SettingStackScreens = () => (
<SettingStack.Navigator>
<SettingStack.Screen name="Profile" component={Profile} />
</SettingStack.Navigator>
);
const Drawer = createDrawerNavigator();
const DrawerScreens = () => (
<Drawer.Navigator>
<Drawer.Screen name="Home" component={HomeStackScreens} />
<Drawer.Screen name="Profile" component={ProfileStackScreens} />
<Drawer.Screen name="Settings" component={SetttingStackScreens} />
</Drawer.Navigator>
);
class MyApp extends React.Component {
render() {
return (
<NavigationContainer>
<DrawerScreens />
</NavigationContainer>
);
}
}
export default MyApp;
All my others screen are in the form "export default class ScreenName extends React.Component". They are imported in App.js to setup the navigation. The initial screen is Home. The icon is showing correctly on the right side of the header. Calling "DrawerActions.toggleDrawer()" directly does nothing.
I tried "this.props.navigation.toggleDrawer()", and it throws error because "this.props" is undefined.
How can I invoke toggleDrawer() with such a navigation setup? Any help is really appreciated!
Here is the final solution I come up with that requires minimal changes to my original code. The key is to receive "navigation" in screenOptions or options, then I can call navigation methods in the children of screenOptions/options.
<HomeStack.Navigator
screenOptions={({navigation}) => ({
headerStyle: {
backgroundColor: '#5C6BC0',
},
headerTintColor: '#fff',
headerRight: () => {
return (
<TouchableOpacity
style={{paddingRight: 8}}
onPress={() => navigation.toggleDrawer()}>
<Icon name="bars" color="#FFF" size={18} />
</TouchableOpacity>
);
},
})}>