How to start Tab Navigation after Onboarding Screen? - react-native

i have the following problem:
I am currently working on a app with react native.
I use 'react-navigation' for the navigation. Now i want to setup an Onboarding Screen, which is only shown at the first start of my application.
This screen should be shown in fullscreen format, nav bar and the tab bar should't be visible.
I already implemented the logic with AsyncStorage, for the Screen itself i use 'react-native-app-intro-slider'.
But how can i set it to be the initial screen? I was able to show it in my very first tab after initial launch of the screen, but then the tab bar is shown as well.
I could potentially hide the tabbar, but after completing the onboarding setup/screen I want the tab bar to be visible again.
Is there a way to show the screen fullscreen and after completing the onboarding to navigate to the Tab Navigator?
I am very new to react native and also javascript in general, sorry if this question is unprecise.
App.
App.js:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Button,
ScrollView,
Statusbar
} from 'react-native';
import { SafeAreaView, TabNavigator, StackNavigator } from 'react-navigation';
import Home from './Tabs/Home';
import Wheel from './Tabs/Wheel';
import Categories from './Tabs/Categories';
import Settings from './Tabs/Settings';
import TabBar from './Tabs/TabBar';
import StrafenScreen from './screens/StrafenScreen';
import VideoScreen from './screens/VideoScreen';
import UberUns from './screens/UberUns';
import Rechtliches from './screens/Rechtliches';
import SprachAuswahl from './screens/Sprachauswahl';
import RandomVideoScreen from './screens/RandomVideoScreen';
import Onboarding from './screens/Onboarding.js';
export const FeedStack = StackNavigator({
Category: {
screen: Categories,
navigationOptions: {
title: 'Kategorien',
},
},
Strafen: {
screen: StrafenScreen,
navigationOptions: ({ navigation }) => ({
title: `${navigation.state.params.key} `,
}),
},
Videos: {
screen: VideoScreen,
navigationOptions: ({ navigation }) => ({
tabBarVisible: (navigation.state.params && navigation.state.params.hideTabBar) === true,
title: `${navigation.state.params.key} `,
}),
},
});
export const WheelStack = StackNavigator({
Wheel: {
screen: Wheel,
navigationOptions: {
title: 'Glücksrad',
},
},
RandomVideo: {
screen: RandomVideoScreen,
navigationOptions: ({ navigation }) => ({
tabBarVisible: (navigation.state.params && navigation.state.params.hideTabBar) === true,
animationEnabled: true
}),
},
Onboarding: {
screen: Onboarding,
navigationOptions: ({ navigation }) => ({
tabBarVisible: (navigation.state.params && navigation.state.params.hideTabBar) === true,
animationEnabled: true
}),
},
});
export const SettingsStack = StackNavigator({
Settings: {
screen: Settings,
navigationOptions: {
title: 'Über uns',
},
},
UberUns: {
screen: UberUns,
navigationOptions: ({ navigation }) => ({
title: `${navigation.state.params.key} `,
}),
},
SprachAuswahl: {
screen: SprachAuswahl,
navigationOptions: ({ navigation }) => ({
title: `${navigation.state.params.key} `,
}),
},
Rechtliches: {
screen: Rechtliches,
navigationOptions: ({ navigation }) => ({
title: `${navigation.state.params.key} `,
}),
},
});
const MainScreenNavigator = TabNavigator({
Home: {screen: Home},
Kategorien: {screen: FeedStack},
Rad: {screen: WheelStack},
Einstellungen: {screen: SettingsStack}
},
{
swipeEnabled:true,
tabBarOptions: {
activeTintColor: 'white',
activeBackgroundColor: 'darkgrey',
inactiveTintColor: 'black',
inactiveBackgroundColor: 'grey',
labelStyle: {
fontSize: 11,
padding: 0
}
}
});
MainScreenNavigator.navigationsOptions = {
title: 'Demo'
};
StackNavigator.navigationOptions = {
headerStyle: {
borderBottomWidth: 0,
}
};
export default MainScreenNavigator;
My First Tab:
import React from 'react';
import {
Text,
View,
Button,
Image,
TouchableHighlight,
TouchableOpacity,
AsyncStorage
} from 'react-native';
import WelcomeScreen from '../screens/WelcomeScreen.js';
import Onboarding from '../screens/Onboarding.js';
import checkIfFirstLaunch from '../components/checkLaunch';
export default class Home extends React.Component {
static navigationOptions = {
tabBarLabel: 'Home',
tabBarIcon: ({tintColor}) => (
<Image
source={require('../images/home.png')}
style={{width: 22, height: 22, tintColor: 'white'}}>
</Image>
)
}
constructor(props) {
super(props);
this.state = {
isFirstLaunch: false,
hasCheckedAsyncStorage: false,
};
}
async componentWillMount() {
const isFirstLaunch = await checkIfFirstLaunch();
this.setState({ isFirstLaunch, hasCheckedAsyncStorage: true });
}
render() {
const { hasCheckedAsyncStorage, isFirstLaunch } = this.state;
const { navigate } = this.props.navigation;
if (!hasCheckedAsyncStorage) {
return null;
}
return isFirstLaunch ?
<Onboarding /> :
<View style={styles.container}>
<TouchableOpacity
style={{ flex: 1,
alignItems: 'center',
justifyContent: 'center', }}
onPress={
() => navigate('Kategorien', {})
}
>
<Image
style={{ width: 230, height: 230, borderWidth: 3, marginTop: 30}}
source={require('../images/final-course-categories.jpg')}
>
</Image>
</TouchableOpacity>
<TouchableOpacity
style={{ flex: 1,
alignItems: 'center',
justifyContent: 'center', }}
onPress={
() => navigate('Rad', {})
}
>
<Image
style={{ width: 230, height: 230, borderWidth: 3}}
source={require('../images/fortuneWheel.png')}
>
</Image>
</TouchableOpacity>
</View>
;
}
}
const styles = {
container: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
buttonContainer: {
flex: 1
}
};
Onboarding component:
import React from 'react';
import { StyleSheet } from 'react-native';
import AppIntroSlider from 'react-native-app-intro-slider';
const styles = StyleSheet.create({
image: {
width: 100,
height: 100,
}
});
const slides = [
{
key: 'somethun',
title: 'Achtung',
text: 'Die Strafen in dieser App sind nur als Spaß gedacht.\nBitte nicht ernst nehmen.',
image: require('../images/warning.png'),
imageStyle: styles.image,
backgroundColor: '#59b2ab',
},
{
key: 'somethun-do',
title: 'Title 2',
text: 'Other cool stuff',
backgroundColor: '#febe29',
},
{
key: 'somethun1',
title: 'Rocket guy',
text: 'Lorem ipsum',
image: require('../images/home.png'),
imageStyle: styles.image,
backgroundColor: '#22bcb5',
}
];
export default class App extends React.Component {
_onDone = () => {
}
static navigatorStyle = {
navBarHidden: true
};
render() {
return (
<AppIntroSlider
slides={slides}
onDone={this._onDone}
/>
);
}
}
How can i even tell my App which screen it should use as the initial screen?
Thanks.

Related

How to use setState or useState with react native bottom tab navigation v4

First of all I want to say sorry because of my bad English here...
I want to use setState or use State hooks in Route.js file I don't know how to do it. If anyone knows the answer - please help me..
I have used asyncstorage but it is not make effect automatically when data has been updated.. it wants refresh or save Route.js file at every moment.
This is my Route.js file
import React from 'react';
import { Button, Image } from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';
import {createStackNavigator} from 'react-navigation-stack';
import HomeScreen from './pages/HomeScreen';
import SettingsScreen from './pages/SettingsScreen';
import DetailsScreen from './pages/DetailsScreen';
import ProfileScreen from './pages/ProfileScreen';
const HomeStack = createStackNavigator(
{
Home: { screen: HomeScreen },
Details: { screen: DetailsScreen },
},
{
defaultNavigationOptions: {
headerStyle: {
backgroundColor: '#42f44b',
},
headerTintColor: '#FFFFFF',
title: 'Home',
},
}
);
const SettingsStack = createStackNavigator(
{
Settings: { screen: SettingsScreen },
Details: { screen: DetailsScreen },
}, // here i have use asycstroage but it is not working properly
{
defaultNavigationOptions: {
headerStyle: {
backgroundColor: '#42f44b',
},
headerTintColor: '#FFFFFF',
title: 'Settings',
},
}
);
const App = createBottomTabNavigator(
{
Home: { screen: HomeStack },
Settings: { screen: SettingsStack },
},
{
defaultNavigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused, horizontal, tintColor }) => {
const { routeName } = navigation.state;
if (routeName === 'Home') {
return ( <Image source={ focused ? require('./asset/home.png') :
require('./asset/bar.png')}
style={{ width: 20,
height: 20,
borderRadius: 40 / 2,
}} />
);
} else if (routeName === 'Settings') {
return ( <Image source={ focused ? require('./asset/setting.png') :
require('./asset/bar.png')}
style={{ width: 20,
height: 20,
borderRadius: 40 / 2,
}} />
);
}
},
}),
}
);
export default createAppContainer(App);
So how can I do it?
And how to pass this state with navigation screen..
Thanks..

How to load custom tab icon in createBottomTabNavigator() in react-native

I am using TabNavigator in StackNavigator, i am able to pass props to TabNavigator from StackNavigator , which has four tabs.
one of the tab which is named profile, has image icon, loading from URL.
i can show image from URL whenever i come from Login or Splash screen.
but the problem is once user change profile picture, i can't update the profile icon in profile tab.
here is my code:
This is Main StackNavigator:
import { createStackNavigator } from 'react-navigation';
import Landing from '../screens/onboarding/Landing';
import PhoneLogin from '../screens/onboarding/PhoneLogin';
import EnterCode from '../screens/onboarding/EnterCode';
import Home from './HomeTaBNavigator';
export default createStackNavigator({
Landing: {
screen: Landing,
navigationOptions: { header: null, }
},
PhoneLogin: {
screen: PhoneLogin,
navigationOptions: { header: null }
},
EnterCode: {
screen: EnterCode,
navigationOptions: { header: null }
},
Home: {
screen: Home,
navigationOptions: { header: null }
},
});
This is TabNavigator:
import React, { Component } from 'react';
import { Image, StyleSheet, View } from 'react-native';
import { createBottomTabNavigator, TabBarBottom } from 'react-navigation';
import Feed from '../screens/home/Feed';
// import Notification from '../screens/home/Notification';
import Notification from './NotificationNavigator';
// import Profile from '../screens/home/Profile';
import Profile from './ProfileNavigator';
// import Search from '../screens/home/Search';
import Search from './SearchNavigator';
import { Colors } from '../theme';
import ImageProgress from 'react-native-image-progress';
const styles = StyleSheet.create({
iconProfileImg: {
overflow: 'hidden',
borderRadius: 12,
width: 24,
height: 24,
resizeMode: 'contain',
alignItems: "flex-start",
justifyContent: 'flex-start',
},
imageContainer: {
borderRadius: 12,
overflow: 'hidden',
width: 24,
height: 24,
alignContent: 'flex-start',
justifyContent: 'flex-start',
},
});
export default createBottomTabNavigator({
Feed: {
screen: Feed,
navigationOptions: ({ navigation }) => ({
header: null,
tabBarIcon: ({ focused, tintColor }) => {
let url = navigation.getParam('userProfileImageUrl');
console.log('userProfileImage in Home BottomTabBar: ', url);
return (focused ? <Image source={require('Frenemys/src/assets/tab_bar_icons/tab_1_active.png')} /> : <Image source={require('Frenemys/src/assets/tab_bar_icons/tab_1.png')} />)
}
})
},
Search: {
screen: Search,
navigationOptions: ({ navigation }) => ({
header: null,
tabBarIcon: ({ focused, tintColor }) => {
let url = navigation.getParam('userProfileImageUrl');
console.log('userProfileImage in Search BottomTabBar: ', url);
return (focused ? <Image source={require('Frenemys/src/assets/tab_bar_icons/tab_2_active.png')} /> : <Image source={require('Frenemys/src/assets/tab_bar_icons/tab_2.png')} />)
}
})
},
Notification: {
screen: Notification,
navigationOptions: ({ navigation }) => ({
header: null,
tabBarIcon: ({ focused, tintColor }) => {
let url = navigation.getParam('userProfileImageUrl');
console.log('userProfileImage in Notification BottomTabBar: ', url);
return (focused ? <Image source={require('Frenemys/src/assets/tab_bar_icons/tab_3_active.png')} /> : <Image source={require('Frenemys/src/assets/tab_bar_icons/tab_3.png')} />)
}
})
},
Profile: {
screen: Profile,
navigationOptions: ({ navigation }) => ({
header: null,
tabBarIcon: ({ focused, tintColor }) => {
let url = navigation.getParam('userProfileImageUrl');
console.log('userProfileImage in Profile BottomTabBar: ', url);
return (
<View style={{ marginTop: -8 }}>
<View style={styles.imageContainer}>
<ImageProgress
style={styles.iconProfileImg}
source={{ uri: url }}
renderError={(error) => {
console.log('error load image: ', error)
return (
<Image
style={styles.iconProfileImg}
source={require('Frenemys/src/assets/additional_icons/profile_fallback.jpg')}
/>
)
}}
/>
</View>
</View>
)
}
}),
},
}, {
tabBarOptions: {
activeTintColor: Colors.app_green,
inactiveTintColor: Colors.inactive_tab_black,
showLabel: false,
style: {
backgroundColor: Colors.white,
},
},
tabStyle: {
width: 100,
//backgroundColor: 'green',
},
// tabBarComponent: props => <TabBar navigation={props.navigation}/>,
lazy: true,
initialRouteName: 'Feed',
});
Now when i change profile picture in EditProfile.js which is child component of Profile Stack Navigator, Now how can i update icon in profile tab??
EditProfile:
i am saving user data in AsyncStorage.
saveUser = async (fromImageUpload, responseData) => {
try {
const data = fromImageUpload ? responseData.data.profile : responseData.data;
console.log('get user: ' + JSON.stringify(data));
await AsyncStorage.setItem(AsyncKeyss.USER, JSON.stringify(data));
return data;
} catch (e) {
// saving error
console.log(e);
}
}
I am able to update profile icon in profile tab whenever i come from Login screen, as i told above.
navigation.navigate(NavigationKeys.Home, { userProfileImageUrl: userImage });
The same way you get a param like let url = navigation.getParam('userProfileImageUrl'); you can just set the param (update the value) when you change the profile picture.
Just call
navigation.setParams({userProfileImageUrl: newUserProfileImageUrl })
With the new image url and it will be updated.

How can TabNavigator child screen refer to parent StackNavigator?

The structure of the application is this.
StackNavigator
StackA-Screen(TabNavigator)
TabChildA-Screen
TabChildB-Screen
...
StackB-Screen
code in App.js
const TabComponent = TabNavigator(
{
TabChildA-Screen: {
screen: TabChildA,
},
TabChildB-Screen: {
screen: TabChildB,
}
},
{
tabBarPosition: "bottom",
animationEnabled: false,
swipeEnabled: false
}
);
const StackComponent = StackNavigator(
{
StackA-Screen: {
screen: TabComponent,
navigationOptions: ({ navigation }) => ({
headerBackTitle: null,
headerRight: (
<TouchableWithoutFeedback
onPress={() =>
navigation.navigate("StackB-Screen", { space: "" }) // can't navigate to "StackB-Screen".
}
>
<MaterialIcon
name="playlist-add"
size={Sizes.NavigationBar.Icon.Size}
style={{ padding: 8, color: Colors.White }}
/>
</TouchableWithoutFeedback>
)
})
},
StackB-Screen: {
screen: StackB,
}
},
{
initialRouteName: "StackA-Screen",
mode: "modal"
}
);
export default StackComponent;
I want to navigate TabChildA-Screen to StackB-Screen.
But, TabChildA-Screen can refer to navigator is navigator of TabNavigator.
code in TabChildA-Screen
import React, { Component } from "react";
import { Button, Text, View } from "react-native";
class StackB extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center"
}}
>
<Button
onPress={ () =>
this.props.navigation.navigate("StackB-Screen") // can't navigate to "StackB-Screen".
}
title="move to StackB-Screen"
/>
</View>
);
}
}
export default StackB;
How to TabChildA-Screenrefer StackNavigator ?

In React Native how to navigate between screens?

I am using React Navigation. I need to navigate from screen1 to screen2. I created tab navigation which include some screens but not screen1. When I click on a button from screen1 to go to screen2 which should show in tabbed screen, it is showing me error.
This is screen1(Main.js)
import React, { Component } from 'react';
import {
ImageBackground,
StyleSheet,
Text,
View,
Modal
} from 'react-native';
import { Container, Header, Left, Content, Footer, FooterTab, Icon, Grid, Row, Button } from 'native-base';
import TabNav from '../screens/Dashboard';
import { Dashboard } from '../screens/Dashboard';
export default class Main extends Component<{}> {
render() {
return (
<Container>
<Grid>
<Row size={2}>
<View style={{alignItems: 'center', flexDirection: 'column', flex: 1, justifyContent: 'space-around' }}>
<View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}>
<Button style={styles.buttonBrowseStyle} onPress={() => this.props.navigation.navigate('Dashboard')}>
<Text>Browse</Text>
</Button>
</View>
</View>
</Row>
</Grid>
</Container>
);
}
}
This is screen2(Dashboard.js)
import React from 'react';
import { Text } from 'react-native';
import { TabNavigator, TabBarBottom } from 'react-navigation';
import Post from './Post';
export const Dashboard = () => {
return (<Text>Dashboard</Text>);
}
const TabNav = TabNavigator ({
Dashboard: {
screen: Dashboard,
},
Post: {
screen: Post,
},
},
{
tabBarComponent: TabBarBottom,
tabBarPosition: 'bottom',
swipeEnabled: false,
animationEnabled: true,
activeBackgroundColor: 'yellow',
tabBarOptions: {
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
},
tabBarIcon: ({focused, tintColor}) => {
const { routeName } = navigation.state;
let iconName;
if(routeName==='Main'){
}
}
}
);
export default TabNav;
Getting this error on clicking "Browse" button.
As the above answer mentioned, you are not including Main Component to your navigation so, you can basically think like they are not connected each other whatsoever.
What I suggest you is having a PrimaryNavigator, you can think as Main component in your case.
const PrimaryNavigator = StackNavigator({
SignInStack: {
screen: SignInStackNavigator
},
SignUpStack: {
screen: SignUpStackNavigator
},
DrawerMainStack: {
screen: MenuDrawerStack
}
},
{
headerMode: 'none'
});
Next step, you can use your TabNavigator as in the below.
const MenuDrawerStack = StackNavigator({
DrawerBar: {
screen: DrawerBar
}
}, {
style: {
leftDrawerWidth: 40
},
index: 0,
navigationOptions: ({ navigation }) => ({
headerStyle: { backgroundColor: '#1874CD' },
gesturesEnabled: false,
headerLeft: <Icon
name="menu"
onPress={() => {
navigation.navigate({
key: null,
index: 0,
action: [
navigation.navigate('DrawerToggle')
]
})
}}
/>
}),
})
And finally, you can build your tab navigator :
const DrawerBar = DrawerNavigator({
Shop: {
screen: ShopTabNavigator
},
}, {
drawerPosition: 'left',
headerMode: 'none',
initialRouteName: 'Shop',
navigationOptions: ({ navigation }) => ({
headerStyle: { backgroundColor: 'white' },
}),
contentComponent: props => <CustomDrawerMenu {...props} />,
drawerOpenRoute: 'DrawerOpen',
drawerCloseRoute: 'DrawerClose',
drawerToggleRoute: 'DrawerToggle'
})
You should customize these but what I wanted to show you is that the methodology for navigation in React Native with react-navigation is pretty much like I showed you above.
And as the last part you have to pass PrimaryNavigator to your application as High Order Component.
export default class Main extends Component<{}> {
render() {
return (
<PrimaryNavigator />
);
}
}
Main should be part of StackNavigator. Navigation props is not available in Main because it is not a screen in any of the Navigator configuration.

react-navigation Cannot read property 'type' of null error in reducer

Project
I am developing draw navigation with reactive navigation. (using redux)
Stack and tap nested navigation work fine
Error
If I add nested drawer navigation, the reducer throws an error.
The error screen is shown below.
This is my full code
https://bitbucket.org/byunghyunpark/luxlab-user-2/commits/all
Error related code
src/navigation/index.js
import React, { Component } from "react";
import { BackHandler } from "react-native";
import { connect } from "react-redux";
import { StackNavigator, DrawerNavigator, addNavigationHelpers, NavigationActions } from "react-navigation";
import NavigationStack from "./navigationStack";
class AppNavigation extends Component {
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
}
onBackPress = () => {
const { dispatch, navigationState } = this.props;
if (navigationState.stateForLoggedIn.index <= 1) {
BackHandler.exitApp();
return;
}
dispatch(NavigationActions.back());
return true;
};
render() {
const { navigationState, dispatch, isLoggedIn } = this.props;
const state = isLoggedIn
? navigationState.stateForLoggedIn
: navigationState.stateForLoggedOut;
return (
<NavigationStack navigation={addNavigationHelpers({ dispatch, state })}/>
);
}
}
const mapStateToProps = state => {
return {
isLoggedIn: state.loginReducer.isLoggedIn,
navigationState: state.navigationReducer
};
};
export default connect(mapStateToProps)(AppNavigation);
src/navigation/navigationStack.js
import { Platform, StyleSheet, Text, View, AsyncStorage, ScrollView } from 'react-native';
import { StackNavigator, TabNavigator, DrawerNavigator, DrawerItems } from 'react-navigation';
import MyRepairWait from '../components/repair/myRepairWait';
import MyRepairProgress from '../components/repair/myRepairProgress';
import MyRepairComplete from '../components/repair/myRepairComplete';
import MySalesWait from '../components/sales/mySalesWait';
import MySalesComplete from '../components/sales/mySalesComplete';
import Home from '../components/home';
import ProductList from '../components/buy/productList';
import PartnerList from '../components/map/partnerList';
import Login from '../components/member/login';
const MyRepairListTab = TabNavigator({
wait: { screen: MyRepairWait, navigationOptions: { tabBarLabel: '문의중' } },
progress: { screen: MyRepairProgress, navigationOptions: { tabBarLabel: '진행중' } },
complete: { screen: MyRepairComplete, navigationOptions: { tabBarLabel: '완료' } }
},
{
tabBarPosition: 'top',
swipeEnabled: true,
animationEnabled: false,
tabBarOptions: {
activeTintColor: '#e91e63',
},
backBehavior: 'none',
}
)
const MySalesListTab = TabNavigator({
wait: { screen: MySalesWait, navigationOptions: { tabBarLabel: '문의중' } },
complete: { screen: MySalesComplete, navigationOptions: { tabBarLabel: '완료' } }
},
{
tabBarPosition: 'top',
swipeEnabled: true,
animationEnabled: false,
tabBarOptions: {
activeTintColor: '#e91e63',
},
backBehavior: 'none',
}
)
const baseRoutes = {
home: { screen: Home },
productList: { screen: ProductList },
myRepairList: { screen: MyRepairListTab },
mySalesList: { screen: MySalesListTab },
partnerList: { screen: PartnerList },
login: { screen: Login },
};
const DrawerRoutes = {
Home: {
name: 'Home',
screen: StackNavigator(baseRoutes, { initialRouteName: 'home' })
},
ProductList: {
name: 'ProductList',
screen: StackNavigator(baseRoutes, { initialRouteName: 'productList' })
},
MyRepairList: {
name: 'MyRepairList',
screen: StackNavigator(baseRoutes, { initialRouteName: 'myRepairList' })
},
MySalesList: {
name: 'MySalesList',
screen: StackNavigator(baseRoutes, { initialRouteName: 'mySalesList' })
},
};
const DrawerNavigatorConfig = {
drawerWidth: 300,
drawerPosition: 'right',
contentComponent: props => <ScrollView><DrawerItems {...props} /></ScrollView>,
contentOptions: {
activeTintColor: '#e91e63',
itemsContainerStyle: {
marginVertical: 0,
},
iconContainerStyle: {
opacity: 1
}
}
}
const navigator =
StackNavigator(
{
Drawer: {
name: 'Drawer',
screen: DrawerNavigator(
DrawerRoutes,
DrawerNavigatorConfig
),
},
...navigator
},
{
headerMode: 'none'
}
);
export default navigator;
src/reducers/index.js
import { combineReducers } from 'redux';
import navigationReducer from './navigationReducer';
import loginReducer from './loginReducer';
const AppReducer = combineReducers({
navigationReducer,
loginReducer
});
export default AppReducer;
src/reducers/navigationReducer.js
import { NavigationActions } from "react-navigation";
import AppNavigator from "../navigation/navigationStack";
import { Login, Logout } from "../actions/actionTypes";
const ActionForLoggedOut = AppNavigator.router.getActionForPathAndParams(
"login"
);
const ActionForLoggedIn = AppNavigator.router.getActionForPathAndParams(
"home"
);
const stateForLoggedOut = AppNavigator.router.getStateForAction(
ActionForLoggedOut
);
const stateForLoggedIn = AppNavigator.router.getStateForAction(
ActionForLoggedIn
);
const initialState = { stateForLoggedOut, stateForLoggedIn };
const navigationReducer = (state = initialState, action) => {
switch (action.type) {
case "##redux/INIT":
return {
...state,
stateForLoggedIn: AppNavigator.router.getStateForAction(
ActionForLoggedIn,
stateForLoggedOut
)
};
case Login:
return {
...state,
stateForLoggedIn: AppNavigator.router.getStateForAction(
ActionForLoggedIn,
stateForLoggedOut
)
};
case Logout:
return {
...state,
stateForLoggedOut: AppNavigator.router.getStateForAction(
NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: "login" })]
})
)
};
default:
return {
...state,
stateForLoggedIn: AppNavigator.router.getStateForAction(
action,
state.stateForLoggedIn
)
};
}
};
export default navigationReducer;
src/components/home.js
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, Button, ImageBackground, TouchableHighlight, Image, ScrollView, Alert, CameraRoll, AsyncStorage } from 'react-native';
import { NavigationActions } from "react-navigation";
import Icon from 'react-native-vector-icons/FontAwesome';
import { connect } from 'react-redux';
const styles = StyleSheet.create({
container: {
flex: 1,
},
mainPhoto: {
flex: 1,
margin: 10,
marginBottom: 0,
justifyContent: 'center',
},
mainPhotoEnd: {
marginBottom: 10
},
mainOpacity: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.5)',
},
mainTitle: {
color: 'white',
fontSize: 30,
marginTop: 20,
marginLeft: 20,
marginRight: 20,
fontWeight: '700',
},
mainDescription: {
flex: 2.3,
marginTop: 5,
marginLeft: 20,
marginRight: 20,
color: 'white',
fontSize: 15,
fontWeight: '400',
},
alignRight: {
textAlign: 'right'
},
backgroundWhite: {
flex: 1,
backgroundColor: 'white'
},
headerRight: {
padding: 10
},
headerLeft: {
padding: 20
}
});
class HomeScreen extends React.Component {
navigate1 = () => {
console.log('click navigate1');
const navigate1 = NavigationActions.navigate({
routeName: "partnerList",
params: { name: "Shubhnik" }
});
this.props.navigation.dispatch(navigate1);
};
navigate2 = () => {
console.log('click navigate2');
const navigate2 = NavigationActions.navigate({
routeName: "myRepairList",
params: { name: "Shubhnik" }
});
this.props.navigation.dispatch(navigate2);
};
static navigationOptions = ({navigation}) => ({
drawerLabel: () => null,
title: 'LUXLAB',
headerStyle: {
backgroundColor: '#fff',
borderBottomWidth: 0,
elevation: 0,
},
headerTitleStyle: {
color: '#000',
fontSize: 20,
textAlign: 'center',
alignSelf: 'center',
},
headerRight: <Icon name="bars" size={30} color="#333" onPress={() => navigation.navigate('DrawerOpen')} style={styles.headerRight}/>,
headerLeft: <Icon name="map-marker" size={30} color="#333" onPress={() => navigation.navigate('partnerList')} style={styles.headerLeft} />
})
async componentDidMount() {
let user_info = await AsyncStorage.getItem('user_info');
user_info = JSON.parse(user_info).key;
console.log('storage1', user_info.key);
console.log('isloggedIn', this.props.isLoggedIn);
}
render() {
return (
<View style={styles.backgroundWhite}>
<TouchableHighlight
style={styles.container}
underlayColor="#fff"
onPress={this.navigate1}>
<ImageBackground
source={require('../assets/imgs/main1.jpg')}
style={[styles.mainPhoto, styles.mainOpacity]}>
<View style={styles.mainOpacity}>
<Text style={styles.mainTitle}>중고 명품 구매</Text>
<Text style={styles.mainDescription}>검증받은 다양한 명품들을{"\n"}간편하게 볼 수 있습니다</Text>
</View>
</ImageBackground>
</TouchableHighlight>
<TouchableHighlight
style={styles.container}
underlayColor="#fff"
onPress={this.navigate2}>
<ImageBackground
source={require('../assets/imgs/main2.jpg')}
style={styles.mainPhoto}>
<View style={styles.mainOpacity}>
<Text style={[styles.mainTitle, styles.alignRight]}>수선 견적 문의</Text>
<Text style={[styles.mainDescription, styles.alignRight]}>몇 가지 정보 입력으로{"\n"}수선 견적을 받아보세요</Text>
</View>
</ImageBackground>
</TouchableHighlight>
<TouchableHighlight
style={styles.container}
underlayColor="#fff"
onPress={this.navigate1}>
<ImageBackground
source={require('../assets/imgs/main3.jpg')}
style={[styles.mainPhoto, styles.mainPhotoEnd]}>
<View style={styles.mainOpacity}>
<Text style={styles.mainTitle}>중고 명품 판매</Text>
<Text style={styles.mainDescription}>몇 가지 정보 입력으로{"\n"}매매 견적을 받아보세요</Text>
</View>
</ImageBackground>
</TouchableHighlight>
</View>
)
}
}
const mapStateToProps = state => ({
isLoggedIn: state.loginReducer.isLoggedIn
});
const Home = connect(mapStateToProps, null)(HomeScreen);
export default Home;
Thanks!