How to import React native navigators? - react-native

I have defined all the navigators in a navigator.js file. I want to import it. How do I do that without getting any errors? This is my navigator.js file.
import React, {Component} from 'react';
import {
Platform,
View,
Button,
SafeAreaView,
} from 'react-native';
import {
createAppContainer,
createDrawerNavigator,
createBottomTabNavigator,
createStackNavigator,
DrawerItems,
} from 'react-navigation';
/** NAVIGATORS DEFINED **/
const WelcomeTabNavigator = createBottomTabNavigator({
Welcome: {screen: WelcomeScreen},
Profile,
Settings,
},
{
tabBarOptions: {
activeTintColor: '#fb9800',
inactiveTintColor: '#7e7b7b',
style: { height: 40,backgroundColor: '#fff',borderTopWidth:0.5,borderTopColor: '#7e7b7b' },
labelStyle: {fontSize: 20}
},
navigationOptions:({navigation}) => {
const {routeName} = navigation.state.routes[navigation.state.index];
return {
headerTitle: routeName
};
}
})
const WelcomeStackNavigator = createStackNavigator({
WelcomeTabNavigator: WelcomeTabNavigator
},
{
defaultNavigationOptions:({navigation}) => {
return {
headerLeft: (
<Icon
style={{paddingLeft: 20}}
onPress={() => navigation.openDrawer()}
name="md-menu"
size={30}
/>
)
};
}
})
const AppDrawerNavigator = createDrawerNavigator({
Welcome: {screen: WelcomeStackNavigator},
},
{
contentComponent:(props) => (
<View style={{flex:1}}>
<SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
<DrawerItems {...props} />
<Button
title="Logout"
onPress={() => {
props.navigation.navigate('Home')
}}
/>
</SafeAreaView>
</View>
),
drawerOpenRoute: 'DrawerOpen',
drawerCloseRoute: 'DrawerClose',
drawerToggleRoute: 'DrawerToggle'
})
const AppStackNavigator = createStackNavigator({
Home: {screen: HomeScreen},
Welcome: {screen: AppDrawerNavigator}
});
const AppContainer = createAppContainer(AppStackNavigator);
This is my app.js file
import React, {Component} from 'react';
import {
Platform,
View,
Button,
SafeAreaView,
} from 'react-native';
import {
createAppContainer,
createDrawerNavigator,
createBottomTabNavigator,
createStackNavigator,
DrawerItems,
} from 'react-navigation';
import Icon from 'react-native-vector-icons/Ionicons';
import HomeScreen from './screens/HomeScreen.js';
import WelcomeScreen from './screens/WelcomeScreen.js';
import Profile from './screens/ProfileScreen.js';
import Settings from './screens/SettingsScreen.js';
class App extends React.Component {
render() {
return <AppContainer />;
}
}
export default App;
This is my index.js file
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
I want to know how to import the navigator.js file and connect these 3 files. My navigator.js file contains different navigators like tab navigator , drawer navigator, stack navigator etc. So how can I import all these in a single attempt?

You can combine all the navigators in one page, as long as you import all the pages.
import WelcomeScreen from './WelcomeScreen.js',
import ProfileScreen from './ProfileScreen.js',
import SettingsScreen from './SettingsScreen.js',
import LogoutScreen from './LogoutScreen.js',
const WelcomeTabNavigator = createBottomTabNavigator({
Welcome: {screen: WelcomeScreen,},
Profile: {screen: ProfileScreen,},
Settings: {screen: SettingsScreen,},
},
const WelcomeStackNavigator = createStackNavigator({
Home: {screen: WelcomeTabNavigator,},
Logout: {screen: LogoutScreen,},
})
class App extends React.Component {
render() {
return <WelcomeStackNavigator />;
}
}
export default App;

I like to tell you very simple way to update use navigation.
Below is an example of your index.js file
import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
import { Main } from './navigation/Main';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
export class App extends Component {
render() {
return (
<View style={ styles.container }>
<Main />
</View>
);
}
}
Then here is your Main.js which is your navigation class. You can declare all your screen here.
import {
createStackNavigator,
createAppContainer,
} from 'react-navigation';
import { FirstScreen } from '../screens/FirstScreen';
import { SecondScreen } from '../screens/SecondScreen';
const RootStack = createStackNavigator({
FirstScreen: {
screen: FirstScreen,
key: 'FirstScreen',
navigationOptions: {
gesturesEnabled: false,
},
},
SecondScreen: {
screen: SecondScreen,
key: 'SecondScreen',
navigationOptions: {
gesturesEnabled: false,
},
},
});
export const Main = createAppContainer(RootStack);
Now you can simply navigate from one screen to other.
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
} from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
class FirstScreen extends Component {
onGetStarted() {
const { navigate } = this.props.navigation;
navigate('SecondScreen');
}
render() {
return (
<View style={ styles.container }>
<TouchableOpacity
style={ styles.welcome }
onPress={ () => this.onGetStarted() }
>
<Text>
Welcome to React Native!
</Text>
</TouchableOpacity>
<Text style={ styles.instructions }>This is screen 1</Text>
</View>
);
}
}
export { FirstScreen };

Related

react-native Drawer Navigation with Tab Navigation

I'm trying to set a top menu and a tab menu in my app. The bottom tabs are working, but the top menu is not displaying. The top menu that I am trying to set is the one we click and the left menu options show.
class App extends Component {
render() {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<AppContainer
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
</Provider>
);
}
}
export default App;
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home!</Text>
</View>
);
}
}
class SettingsScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Settings!</Text>
</View>
);
}
}
const TabNavigator = createBottomTabNavigator({
Home: HomeScreen,
Settings: SettingsScreen,
});
const MainStackNavigator = createStackNavigator({
Home: {
screen: TabNavigator
}
});
const AppDrawerNavigator = createDrawerNavigator({
Home:{
screen: MainStackNavigator
}
});
const AppSwitchNavigator = createSwitchNavigator({
Login: { screen: Login },
Main: { screen: AppDrawerNavigator }
});
const AppContainer = createAppContainer(AppSwitchNavigator);
I'm new with react native, so I am not sure the order to set the navigator options. What I'm doing wrong?
Thanks
I've put some code as an example with a MainDrawerNavigator that contains a MainTabNavigator. The tab navigator contains three stack navigators for this purpose I'll only reference the HomeScreenNavigator which is a stack navigator. By default this will show a stack header inside my Home tab but will not show a drawer icon to open the drawer. In order to do this you need to put an icon in to toggle the drawer. I've shown this by accessing the navigationOptions in the HomeScreen specifically shown:
static navigationOptions = (navData) => {
return {
headerLeft: (
<View style={styles.headerButtonLeft}>
<HeaderButtons HeaderButtonComponent={DefaultHeaderButton}>
<Item title="menu" iconName="ios-menu" onPress={() => {
navData.navigation.toggleDrawer()
}} />
</HeaderButtons>
</View>
),
}
}
The above will set an a header button on the left of the HomeScreen and pressing the Item will trigger toggling the drawer open via navData.navigation.toggleDrawer(). Your example would be similar except your outermost navigator would be your switch navigator it seems.
Full code as an example shown below: (let me know if clarification is needed elsewhere).
HomeScreen example:
class HomeScreen extends React.Component {
constructor(props) {
super(props)
this.state = { ... }
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home!</Text>
</View>
);
}
static navigationOptions = (navData) => {
return {
headerLeft: (
<View style={styles.headerButtonLeft}>
<HeaderButtons HeaderButtonComponent={DefaultHeaderButton}>
<Item title="menu" iconName="ios-menu" onPress={() => {
navData.navigation.toggleDrawer()
}} />
</HeaderButtons>
</View>
),
}
}
}
HomeScreenNavigator example:
import { createStackNavigator } from 'react-navigation-stack';
import HomeScreen from '../screens/HomeScreen';
import MediaSelectScreen from '../screens/MediaSelectScreen';
import FinalizePostScreen from '../screens/FinalizePostScreen';
import { userInterface } from '../constants/Colors';
import Styles from '../constants/Styles';
const HomeScreenNavigator = createStackNavigator({
Home: HomeScreen,
MediaSelect: MediaSelectScreen,
FinalizePost: FinalizePostScreen
}, {
defaultNavigationOptions: {
headerStyle: {
backgroundColor: userInterface.accentColor,
height: Styles.HEADER_HEIGHT,
},
}
});
export default HomeScreenNavigator;
MainTabNavigator example:
import { createBottomTabNavigator } from 'react-navigation-tabs';
import MessagesScreen from '../screens/MessagesScreen';
import HomeScreenNavigator from './HomeScreenNavigator';
import LearnScreenNavigator from './LearnScreenNavigator';
const MainTabNavigator = createBottomTabNavigator({
LearnScreen: { screen: LearnScreenNavigator, navigationOptions: () => ({
tabBarLabel: 'Learn'
})},
HomeScreen: { screen: HomeScreenNavigator, navigationOptions: {
tabBarLabel: 'Home'
}},
MessagesScreen: { screen: MessagesScreen, navigationOptions: {
tabBarLabel: 'Messages'
}},
});
export default MainTabNavigator;
MainDrawerNavigator example:
import { createDrawerNavigator } from 'react-navigation-drawer';
import { createAppContainer } from 'react-navigation';
import MainTabNavigator from './MainTabNavigator';
const MainDrawerNavigator = createDrawerNavigator({
DrawerNav: MainTabNavigator
}, {
drawerType: 'slide'
});
export default createAppContainer(MainDrawerNavigator);
App.js example:
import React from 'react';
import * as Font from 'expo-font';
import { AppLoading } from 'expo';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import AppSwitchNavigator from './navigation/AppSwitchNavigator';
export default class App extends React.Component {
state = { ... }
render() {
return (
<Provider store={store}>
<AppSwitchNavigator/>
</Provider>
);
}
}
const store = createStore(rootReducer);
const rootReducer = combineReducers({ ... });

How can I show the Drawer (SideMenu) on any screen except in the login using React Native?

I had several problems trying to achieve this.
The sidemenu is not displayed on the Login screen, but in the Home component yes(this is fine).
But if I go back to the login component (by clicking on the menu navigation item), drawer is now shown from the login (It only must be showed on the Home component). I do not know why the template that I have to put in the drawer is not shown, by default the routes that I have created appear and with this the problem occurs (I am trying to put a template in the sidemenu)..
How can I fix this?
this is my code:
app.js
import React from "react";
import { StyleSheet, View } from "react-native";
import UserNavigation from "./app/navigation/UserNavigation";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return <UserNavigation />;
}
}
userNavigation.js
import React from "react";
import {
Platform,
StyleSheet,
Text,
View,
SafeAreaView,
ScrollView,
Dimensions,
Image
} from "react-native";
import { createDrawerNavigator, DrawerItems } from "react-navigation-drawer";
import { createAppContainer, createSwitchNavigator } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import { Icon } from "native-base";
import LoginScreen from "../screens/login/Login";
import HomeScreen from "../screens/home/Home";
const { width } = Dimensions.get("window");
const CustomDrawerNavigation = props => {
return (
<SafeAreaView style={{ flex: 1 }}>
<View
style={{
height: 250,
backgroundColor: "#fff",
opacity: 0.9
}}
>
<View
style={{
height: 200,
backgroundColor: "Green",
alignItems: "center",
justifyContent: "center"
}}
>
<Image
source={require("../../assets/img/logo.webp")}
style={{ resizeMode: "contain", width: "100%" }}
/>
</View>
<View
style={{
height: 50,
backgroundColor: "Green",
alignItems: "center",
justifyContent: "center"
}}
></View>
</View>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
<View style={{ left: 20, bottom: 20 }}>
<View style={{ flexDirection: "row" }}>
<View
onPress={() => props.navigation.navigate("Login")}
style={{
flexDirection: "row",
alignItems: "flex-start",
justifyContent: "center",
marginRight: 15
}}
>
<Icon
type="MaterialCommunityIcons"
name="logout"
style={{ fontSize: 24 }}
onPress={() => props.navigation.navigate("Login")}
/>
<Text>Salir</Text>
</View>
</View>
</View>
</SafeAreaView>
);
};
const DrawerStack = createStackNavigator({
Home: HomeScreen
});
const DrawerNavigation = createDrawerNavigator({
Home: {
name: "Home",
screen: HomeScreen
},
Login: {
name: "Cerrar Sesión",
screen: LoginScreen
}
});
const AppNavigator = createSwitchNavigator(
{
App: DrawerNavigation,
Login: {
screen: LoginScreen
}
},
{
initialRouteName: "Login",
drawerPosition: "left",
I have another problem and I don't know why the template (CustomDrawerNavigation) I have to put in the drawer is not shown.
contentComponent: CustomDrawerNavigation,
drawerOpenRoute: "DrawerOpen",
drawerCloseRoute: "DrawerClose",
drawerToggleRoute: "DrawerToggle",
drawerWidth: (width / 3) * 2
}
);
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;
login.js
import React, { Component } from "react";
import { View } from "react-native";
import { Button, Text } from "native-base";
export default class Login extends Component {
constructor() {
super();
this.state = {};
}
handlerLogin = async () => {
this.props.navigation.navigate("Home");
};
render() {
return (
<View>
<Text>Login</Text>
<Button block button onPress={() => this.handlerLogin()}>
<Text>Go to home</Text>
</Button>
<Text>Login</Text>
</View>
);
}
}
home.js
import React, { Component } from "react";
import { StyleSheet } from "react-native";
import { StatusBar } from "react-native";
import {
Container,
Header,
Title,
Left,
Icon,
Right,
Button,
Body,
Content,
Text,
Card,
CardItem
} from "native-base";
export default class Home extends Component {
constructor() {
super();
this.state = {
loading: false
};
}
closeDrawer = () => {
this.drawer._root.close();
};
openDrawer = () => {
this.drawer._root.open();
};
render() {
return (
<Container>
<Header>
<Left>
<Button
transparent
onPress={() => this.props.navigation.openDrawer()}
>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>HomeScreen</Title>
</Body>
<Right />
</Header>
<Content padder>
<Card>
<CardItem>
<Body>
<Text>Home</Text>
</Body>
</CardItem>
</Card>
</Content>
</Container>
);
}
}
For this you can create two Navigators.
Advantages:
1. After login he cant get back to Login screen if he press back
2. Side Drawer wont be visible in Login Page
Imports we need:
import { createAppContainer, createSwitchNavigator } from 'react-navigation'; import { createStackNavigator } from 'react-navigation-stack'; import { createDrawerNavigator } from 'react-navigation-drawer';
Login Stack:
const LoginStack = createStackNavigator(
{
Login: {
screen: Login,
navigationOptions: {
title: 'Login',
headerLeft: null,
header: null
}
},
forgotPassword: {
screen: ForgotPassword,
navigationOptions: {
title: 'Forgot Password'
}
}
},
{
initialRouteName: 'Login',
} );
Home Page Stack:
const homePageBottomNavigationStack = createStackNavigator(
{
Home: {
screen: Login,
navigationOptions: {
title: 'Login',
headerLeft: null,
header: null
},
},
{
initialRouteName: 'Home',
} )
Drawer Navigator:
const PostLoginStack = createDrawerNavigator(
{
Home: {
screen: homePageBottomNavigationStack
}
} );
Switch Navigator:
const switchNavigator = createSwitchNavigator(
{
LoginStack: LoginStack,
PostLoginStack: PostLoginStack
},
{ headerMode: "none", initialRouteName: "LoginStack" } );
const AppContainer = createAppContainer(switchNavigator);
package.json:
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.5.1",
"react-native-paper": "^3.2.1",
"react-native-reanimated": "^1.4.0",
"react-navigation": "^4.0.10",
"react-navigation-drawer": "^2.3.3",
"react-navigation-material-bottom-tabs": "^2.1.5",
"react-navigation-stack": "^1.10.3"
For Having a custom drawer component, make this change:
const PostLoginStack = createDrawerNavigator(
{
Home: {
screen: homePageBottomNavigationStack
}
},
{
contentComponent: YourCustomDrawerComponent
}
);
You will need to create two navigators one for the Login and one for the App and then wrap them into a SwitchNavigator
So
Login = StackNavigator
App = DrawerNavigator
and Login and App together into a SwitchNavigator
You can refer this article
https://medium.com/building-with-react-native/routing-in-react-native-apps-and-how-to-configure-your-project-with-react-navigation-library-d8d58005bfe9

How to display the menu list from API in DrawerNavigator

I have created the side menu using DrawerNavigator with the static menu names and screens. I want the menu names and screens to be dynamic. Meaning to say I like to fetch those details in API and display in the DrawerNavigator. Please help to resolve this.
const MyApp = createDrawerNavigator({
HomeScreen: {
screen: HomeScreen,
},
WebMenuScreen: {
screen: WebMenuScreen,
},
}, {
drawerPosition: 'right',
},{
contentComponent: CustomDrawerComponent
}, {
initialRouteName: 'Login'
});
Try this, I hope this will helps you.
in Route File
import DrawerNavigator from "./DrawerNavigator";
import Home from './Home';
import About from './About'
import {
createStackNavigator,
createAppContainer,
} from "react-navigation";
const MainNavigator = createStackNavigator({
DrawerNavigator: {
screen: DrawerNavigator,
navigationOptions: {
header: null
}
},
Home: {
screen: Home,
navigationOptions: {
htitle: 'Home'
}
},
About: {
screen: About,
navigationOptions: {
htitle: 'About'
}
},
});
const Routes = createAppContainer(MainNavigator);
export default Routes;
in DrawerNavigator File
import React from 'react';
import { Platform, Dimensions } from 'react-native';
import { createDrawerNavigator, createAppContainer } from 'react-navigation';
import Home from './Home';
import About from '/About'
import MenuDrawer from './MenuDrawer';
const WIDTH = Dimensions.get('window').width;
const DrawerConfig = {
drawerWidth: WIDTH*0.83,
contentComponent: ({ navigation }) => {
return(<MenuDrawer navigation={navigation} />)
}
}
const DrawerNavigator = createDrawerNavigator(
{
Home:{
screen:Home
},
About:{
screen:About
},
},
DrawerConfig
);
export default createAppContainer(DrawerNavigator);
in Menu Drawer File
import React from "react";
import {
View,
Text,
ScrollView,
Image,
TouchableOpacity,
} from "react-native";
var obj = JSON.parse('{ "name":"Home","name":"About" }');
// import styles from './menuDrawerStyles'
class MenuDrawer extends React.Component {
navLink(nav, text) {
return (
<TouchableOpacity
style={{ height: 50 }}
onPress={() => this.props.navigation.navigate(nav)}
>
<Text style={styles.link}>{text}</Text>
</TouchableOpacity>
);
}
render() {
return (
<View style={styles.container}>
<ScrollView style={styles.scroller}>
{
this.obj.map((data) => {
<View style={styles.bottomLinks}>
<View style={{ flex: 2, flexDirection: "row" }}>
{this.navLink(data.name, data.name)}
</View>
<View style={{ flex: 2, flexDirection: "row" }}>
{this.navLink(data.name, data.name)}
</View>
</View>
})
}
</ScrollView>
</View>
);
}
}
in Menu Button File
import React from "react";
import { StyleSheet , Platform } from "react-native";
import Icon from "react-native-vector-icons/MaterialIcons";
export default class MenuButton extends React.Component {
render() {
return (
<Icon
name="reorder"
color="black"
size={25}
style={styles.menuIcon}
onPress={() => this.props.navigation.toggleDrawer()}
/>
);
}
}
const styles = StyleSheet.create({
menuIcon: {
zIndex: 9,
position: "absolute",
top: Platform.OS === "android" ? 15 : 25,
left: 20
}
});
In Menu Drawer file you can call Api and fetch menu list.

Error: undefined is not an object (evaluating 'this.props.navigation.navigate')

I have created a separate route file and when I am trying to navigate between screens with the help of these routes with react-navigation using stackNavigator I am getting this error I have already tried other solutions available on Stack overflow but none of the answers solve my problem here is my code.
This is my Route.js file
import { createAppContainer, createStackNavigator } from 'react-navigation';
import Login from './screens/Login';
import Register from './screens/Register';
import Start from './screens/Start';
const AppNavigator = createStackNavigator({
Home: {
screen: Start,
},
LoginScreen: {
screen: Login,
},
RegisterScreen: {
screen: Register,
},
}, {
initialRouteName: 'Home',
navigationOptions: {
header: null
}
});
export default createAppContainer(AppNavigator);
And this is my component where I am trying to navigate
import React,{ Component } from 'react';
import { StyleSheet, View, KeyboardAvoidingView,Text } from 'react-native';
import NewButtons from './NewButtons';
import Logo from './Logo';
export default class Start extends Component{
constructor () {
super();
}
loginPress = () => {
this.props.navigation.navigate('LoginScreen');
}
registerPress = () => {
this.props.navigation.navigate('RegisterScreen');
}
render(){
return(
<KeyboardAvoidingView behavior='padding' style={styles.wrapper}>
<View style={styles.logoContainer}>
<Logo/>
<Text style={styles.mainHead}>Welcome to Food Zone</Text>
<Text style={{margin: 10, textAlign:'center'}}>Check out our menus, order food and make reservations{"\n"}{"\n"}</Text>
<NewButtons text="Login"
onPress={this.loginPress}/>
<NewButtons text="Register"
onPress={this.registerPress}/>
</View>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
logoContainer: {
alignItems: 'center',
},
mainHead: {
fontFamily: 'PatuaOne',
color: '#ff9900',
fontSize: 28,
marginTop: -50,
},
})
And this in my button component
import React,{ Component } from 'react';
import { StyleSheet, View,Dimensions } from 'react-native';
import { Button, Text } from 'native-base';
const {width:WIDTH} = Dimensions.get('window')
export default class NewButtons extends Component{
constructor(props){
super(props);
}
handlePress = () => {
this.props.onPress();
}
render(){
return(
<View style={styles.ButtonContainer}>
<Button light style={styles.mainButtons} onPress={this.handlePress()}>
<Text style={styles.textProps}>{this.props.text}</Text>
</Button>
</View>
);
}
}
const styles = StyleSheet.create({
textProps:{
fontFamily: 'PatuaOne',
color: '#ffffff',
},
mainButtons: {
backgroundColor: "#ff9900",
width: 250,
margin: 5,
color: '#ffffff',
justifyContent: 'center',
width: WIDTH -75,
borderRadius: 10,
},
ButtonContainer: {
alignItems: 'center',
}
})
I managed to remove this error by importing routes in App.js file and by calling it in index.js here is my code of App.js file.
import React, {Component} from "react";
import Routes from "./Routes";
const App = () => <Routes/>
export default App;

Question on Auth Flow and React Navigation (React Native)

I’m trying to setup the Auth flow with my app, but I can’t seem to figure it out exactly. Here’s how I’d like the flow to be, but please let me know if you have any repositories that might help for this:
Tabs:
Home
Search
Screens:
AuthLoading
Login
Home
Search
Search
Auth Flow:
App launches, checks for userToken
If userToken, redirect to Home
Screen (With Bottom Tab Bar)
If no userToken, redirect to Login Screen (Login Screen has Facebook OAuth from Expo)
User logins with Facebook and checks firebase If success, redirect to Home Screen (With Bottom Tab Bar) 4. If fail, redirect to Login Screen
router.js
import React from 'react';
import { Platform, StatusBar } from 'react-native';
import { createStackNavigator, createBottomTabNavigator, createSwitchNavigator } from 'react-navigation';
import { FontAwesome } from 'react-native-vector-icons';
import AuthLoadingScreen from '../screens/AuthLoadingScreen';
import LoginScreen from '../screens/LoginScreen';
import HomeScreen from '../screens/HomeScreen';
import SearchScreen from '../screens/SearchScreen';
export const UnauthenticatedStack = createStackNavigator({
AuthLoading: {
screen: AuthLoadingScreen,
navigationOptions: {
title: 'AuthLoading',
tabBarVisible: false,
header: null,
headerLeft: null,
headerRight: null,
},
},
Login: {
screen: LoginScreen,
navigationOptions: {
title: 'Login',
tabBarVisible: false,
header: null,
headerLeft: null,
},
},
});
export const AuthenticatedStack = createBottomTabNavigator(
{
Home: {
screen: HomeScreen,
navigationOptions: {
tabBarLabel: 'Home',
tabBarIcon: ({ tintColor }) => (
<FontAwesome name="home" size={24} color={tintColor} />
),
},
},
Search: {
screen: SearchScreen,
navigationOptions: {
tabBarLabel: 'Search',
tabBarIcon: ({ tintColor }) => (
<FontAwesome name="search" size={24} color={tintColor} />
),
},
},
},
);
export default createSwitchNavigator({
Home: AuthenticatedStack,
Login: UnauthenticatedStack,
},
{
initialRouteName: 'Home'
,
});
App.js
// Imports: Dependencies
import React from 'react';
import { View, StyleSheet } from 'react-native';
import firebase from 'firebase';
import { FirebaseAPIKey, authDomain, databaseURL, projectId, messagingSenderId } from './config/config';
import { UnauthenticatedStack, AuthenticatedStack } from './navigation/router';
// Firebase Config
export const firebaseConfig = {
apiKey: FirebaseAPIKey,
authDomain: `${authDomain}`,
databaseURL: `${databaseURL}`,
projectId: `${projectId}`,
// storageBucket: "",
messagingSenderId: `${messagingSenderId}`,
};
console.log(firebaseConfig)
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// React Native: Application
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<UnauthenticatedStack />
</View>
);
}
};
// Styles
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#CA3433',
},
});
AuthLoading.js
import React from 'react';
import { ActivityIndicator, AsyncStorage, StatusBar, StyleSheet, View, Text } from 'react-native';
export default class AuthLoadingScreen extends React.Component {
constructor(props) {
super(props);
this.checkUserToken();
}
async checkUserToken() {
const userToken = await AsyncStorage.getItem('userToken');
// If User Token
if (userToken) {
AsyncStorage.setItem(userToken);
this.props.navigation.navigate('Home');
}
else {
this.props.navigation.navigate('Login');
}
}
// Render any loading content that you like here
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>Checking Authentication</Text>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
// Styles
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#CA3433',
justifyContent: 'center',
alignItems: 'center',
},
text: {
justifyContent: 'center',
color: '#fff',
fontSize: 18,
fontWeight: '500',
},
});
Home.js
// Imports: Dependencies
import React from 'react';
import { View, StyleSheet } from 'react-native';
// Imports: Components
import List from '../components/List';
// React Native Screen: Home
export default () => (
<View style={styles.container}>
<List />
</View>
);
// Styles
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
},
});
Search.js
// Imports: Dependencies
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
// Imports: Components
// React Native Screen: Search
export default class Search extends Component {
// Render
render() {
return (
<View styles={styles.container}>
<Text>Search</Text>
</View>
)
}
}
// Styles
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
In App.js, do not export firebase config part.
App class should be like that:
export default class App extends React.Component {
componentWillMount() {
const firebaseConfig = {
apiKey: FirebaseAPIKey,
authDomain: `${authDomain}`,
databaseURL: `${databaseURL}`,
projectId: `${projectId}`,
// storageBucket: "",
messagingSenderId: `${messagingSenderId}`,
}
firebase.initializeApp(config);
}
render() {
return (
<View style={styles.container}>
<UnauthenticatedStack />
</View>
)
}
};
Move AuthLoadingScreen to createSwitchNavigator:
const rootNavigator = createSwitchNavigator({
Home: AuthenticatedStack,
Login: UnauthenticatedStack,
AuthLoading: AuthLoadingScreen,
},
{
initialRouteName: 'AuthLoading',
});
export const AppNavigation = createAppContainer(rootNavigator)
App.js
// React Native: Application
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<AppNavigation />
</View>
);
}
};