We almost created the same structure as Codecademy Go. Our nested tab and stack navigators can handle most of the app already. But, before users can access the app, they need to authenticate first. Without an account, we can’t keep track of the user’s progress.
To prevent users from accidentally opening screens where they shouldn’t be, we have to “remove” the authenticated screens. react-navigation
allows us to do this by dynamically changing the navigator screen components. When changing these screens, react-navigation
automatically moves the users over to the right screen.
Instead of using a stack navigator within a tab navigator, we will add a stack navigator as our first navigator.
Instructions
Let’s start with a simple stack navigator and two screens - LoginScreen
and FeedScreen
. In this code, we added a context-based state value to keep track of the authentication state. We won’t go into too much detail with the context, if you are unfamiliar with context, check out the documentation.
Right now, we render the FeedScreen
without the ability to logout of our app. Add a Button
to the FeedScreen
that changes the user to false
when pressed.
Good! In the real world, users would enter their email or username and a password to authenticate. Let’s keep it simple in our code and only use a similar button to authenticate.
Add another button to the LoginScreen
that changes the user to true
when pressed.
Perfect, we are almost there! We need to render the LoginScreen
or FeedScreen
, depending on the current authentication state. We can add this dynamic behavior to our stack navigator.
Change the AppNavigator
only to render the LoginScreen
when we don’t have a user. When we do have a user, only render the FeedScreen
.
Awesome! If you press the button, you should see the right screen. react-navigation
supports this behavior out of the box, without the need to manually navigate users.
Press run to continue.