Reputation: 333
I am looking to add methods to handle authentication to the Component Returned by createStackNavigator. How can I do this?
It seems like it would make sense to do it at this level as it is the component that holds the entire application.
Upvotes: 0
Views: 256
Reputation: 111
There is something called a switch navigator in react-navigation which helps you to select navigators based on the authentication of a user. For example, let us suppose you have two navigators, LoggedInNavigator and LoggedOutNavigator. You can use the SwtichNavigator to toggle between these navigators on the basis of authentication status.
However there is also another way to do this. That is to have 3 navigators; RootNavigator, LoggedInNavigator and LoggedOutNavigator. You can set the default route of the navigator by sending a var which specifies if the user is authenticated or not.
In App.js
import { CreateRootNavigator } from RootNavigator.js; // the below file
class App extends React.component {
render() {
const isAuthenticated = this._getAuthState(); // contains a boolean variable if user is authenticated or not
const RootNavigator = createRootNavigator(isAuthenticated)
return {
<RootNavigator />
}
}
}
export default App;
In RootNavigator.js
import { LoggedInNavigator } from "./LoggedInNavigation";
import { LoggedOutNavigator } from "./LoggedOutNavigation";
export const CreateRootNavigator = (loggedIn = false) => {
return createStackNavigator({
LoggedIn: {
screen: LoggedInNavigator,
navigationOptions: {
gesturesEnabled: false
}
},
LoggedOut: {
screen: LoggedOutNavigator,
navigationOptions: {
gesturesEnabled: false
}
}
},
{
headerMode: "none",
mode: "modal",
initialRouteName: loggedIn ? "LoggedIn" : "LoggedOut"
});
};
Upvotes: 1