'React Native InitialRouteName
I'm using React Native v5.0 and trying to set a nested navigation for my app, however, the prop "initialRouteName" don't seem to work, even if i set it alone without any React Redux code or the nested function it still wont work, how is that prop supposed to work?
import { useSelector } from 'react-redux';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import SignIn from './pages/SigIn';
import SignUp from './pages/SignUp';
import Dashboard from './pages/Dashboard';
const AppStack = createStackNavigator();
const Tab = createBottomTabNavigator();
function Home() {
return (
<Tab.Navigator>
<Tab.Screen name="Dashboard" component={Dashboard} />
</Tab.Navigator>
);
}
export default function Routes() {
const Signed = useSelector((state) => state.auth.signed);
return (
<NavigationContainer>
<AppStack.Navigator
initial={Home}
initialRouteName={Signed ? Home : SignIn}
screenOptions={{ headerShown: false }}
>
<AppStack.Screen name="SignIn" component={SignIn} />
<AppStack.Screen name="SignUp" component={SignUp} />
<AppStack.Screen name="Home" component={Home} />
</AppStack.Navigator>
</NavigationContainer>
);
}```
Solution 1:[1]
you forgot strings
initialRouteName={Signed ? "Home" : "SignIn"}
Solution 2:[2]
According to the documentation, we should not keep authorized screens and non-authorized screens in one stack. This is so called pattern of "protected routes". Each stack may have its own initialRouteName
https://reactnavigation.org/docs/5.x/auth-flow
isSignedIn ? (
<>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Profile" component={ProfileScreen} />
<Stack.Screen name="Settings" component={SettingsScreen} />
</>
) : (
<>
<Stack.Screen name="SignIn" component={SignInScreen} />
<Stack.Screen name="SignUp" component={SignUpScreen} />
</>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hagai Harari |
Solution 2 | Alex Aymkin |