Not Navigating TO specific Screen in react native - react-native

I am New to react native :
I have created Two files "Browse.js" and "Drawer.js"
I have some Buttons in "Browse.js" But when I Wrap Up my Complete "Browse.js" in "Drawer.js"
like this:=>
import React, { Component } from "react";
import { Image, StyleSheet, ScrollView, TextInput, View } from "react-native";
import Slider from "react-native-slider";
import { AntDesign } from "#expo/vector-icons";
import { Foundation } from "#expo/vector-icons";
import { FontAwesome } from "#expo/vector-icons";
import { Ionicons } from "#expo/vector-icons";
import { MaterialCommunityIcons } from "#expo/vector-icons";
import { RoleLogin } from "./Browse";
import Browse from "./Browse";
import { createDrawerNavigator } from "#react-navigation/drawer";
import { NavigationContainer } from "#react-navigation/native";
import Login from "./Login"
import { Divider, Button, Block, Text, Switch } from "../components";
import { theme, mocks } from "../constants";
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Browse" openByDefault>
<Drawer.Screen name="Browse" component={Browse} />
</Drawer.Navigator>
</NavigationContainer>
);
}
then I cant navigate To specific screen from here means from Drawer screen:
Showing error like this => The action 'NAVIGATE' with payload was not handled by any navigator.
Here Is My Browse.js
import React, { Component } from "react";
import {
Dimensions,
Image,
StyleSheet,
ScrollView,
TouchableOpacity,
View,
} from "react-native";
import { ThemeColors } from "react-navigation";
import { Card, Badge, Button, Block, Text } from "../components";
import { theme, mocks } from "../constants";
import Settings from "./Settings";
import { NotificationsScreen, App } from "./Settings";
const { width } = Dimensions.get("window");
const Drawer = createDrawerNavigator();
import { createDrawerNavigator } from "#react-navigation/drawer";
import { NavigationContainer } from "#react-navigation/native";
import Drawer1 from "./Settings";
import Home from "./Settings";
class Browse extends Component {
state = {
// active: "Products",
// active: "Select_Acivity",
categories: [],
error: [],
// data: [],
roles: "",
username: "",
password: "",
lading: false,
title: "",
data: "",
};
//++++++++++++++++++++++++++++++Drawer fun start++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++Drawer fun close++++++++++++++++++++++++++++++++++
//*******************navagte to setting when data fetch start*************************/
RoleLogin() {
// const { data } = this.state;
// const { username, password, roles } = this.state;
fetch(
"https://jsonplaceholder.typicode.com/todos/1",
//fetch(
// "https://nasdigital.tech/Android_API_CI/validate_login_details",
{
method: "GET",
headers: { "Content-Type": "application/json" },
// body: JSON.stringify([{ data}]),
}
)
.then((response) => response.json())
.then((json) => {
//login to check details from server and then display or navigate to another screen
if (json != "error") {
// if (response && response.length && response[0].message != "error")
alert(JSON.stringify(json));
this.props.navigation.navigate("Drawer", {
data: json.title,
});
// .navigate("Settings", { data: json.title });
// this.props.navigation.navigate("Settings",{data : json.title});
} else {
alert("Cehck Details");
}
})
.catch((error) => alert("Cehck Details"));
}
//*******************navagte to setting when data fetch close**************************** */
componentDidMount() {
this.setState({ categories: this.props.categories });
}
// handleTab = tab => {
// const { categories } = this.props;
// const filtered = categories.filter(category =>
// category.tags.includes(tab.toLowerCase())
// );
// this.setState({ active: tab, categories: filtered });
// };
renderTab(tab) {
const { active } = this.state;
const isActive = active === tab;
return (
<TouchableOpacity
key={`tab-${tab}`}
onPress={() => this.handleTab(tab)}
style={[styles.tab, isActive ? styles.active : null]}
>
<Text size={16} medium gray={!isActive} secondary={isActive}>
{tab}
</Text>
</TouchableOpacity>
);
}
render() {
const { profile, navigation } = this.props;
const { categories } = this.state;
// // const tabs = ["Products", "Inspirations", "Shop"];
// const tabs = ["Select_Activity", "Market_Visit"];
// const tabs = ["Select_Activity"];
const tabs = [""];
return (
<Block>
<Block flex={false} row center space="between" style={styles.header}>
<Text h1 bold>
Select Activity
</Text>
<Button onPress={() => this.RoleLogin()}>
<Image source={profile.avatar} style={styles.avatar} />
</Button>
{/* <Button onPress={() => navigation.navigate("Settings")}>
<Image source={profile.avatar} style={styles.avatar} />
</Button> */}
</Block>
<Block flex={false} row style={styles.tabs}>
{tabs.map((tab) => this.renderTab(tab))}
</Block>
<ScrollView
showsVerticalScrollIndicator={false}
style={{ paddingVertical: theme.sizes.base * 2 }}
>
<Block flex={false} row space="between" style={styles.categories}>
{categories.map((category) => (
<TouchableOpacity
key={category.name}
onPress={() => navigation.navigate("MarketVisit", { category })}
>
<Card center middle shadow style={styles.category}>
<Badge
margin={[0, 0, 15]}
size={90}
color="rgb(255, 163, 102)"
>
<Image source={category.image} />
</Badge>
<Text medium height={20}>
{category.name}
</Text>
<Text gray caption>
{category.count}
</Text>
</Card>
</TouchableOpacity>
))}
</Block>
</ScrollView>
</Block>
);
}
}
//+++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++
Browse.defaultProps = {
profile: mocks.profile,
categories: mocks.categories,
};
export default Browse;
const styles = StyleSheet.create({
header: {
paddingHorizontal: theme.sizes.base * 2,
},
avatar: {
height: theme.sizes.base * 1.0,
width: theme.sizes.base * 1.5,
},
tabs: {
borderBottomColor: theme.colors.gray2,
borderBottomWidth: StyleSheet.hairlineWidth,
marginVertical: theme.sizes.base,
marginHorizontal: theme.sizes.base * 2,
},
tab: {
marginRight: theme.sizes.base * 7,
paddingBottom: theme.sizes.base,
},
active: {
borderBottomColor: theme.colors.secondary,
borderBottomWidth: 3,
},
categories: {
flexWrap: "wrap",
paddingHorizontal: theme.sizes.base * 1.5,
marginBottom: theme.sizes.base * 2,
},
category: {
// this should be dynamic based on screen width
minWidth: (width - theme.sizes.padding * 2.4 - theme.sizes.base) / 2,
maxWidth: (width - theme.sizes.padding * 2.4 - theme.sizes.base) / 2,
maxHeight: (width - theme.sizes.padding * 2.4 - theme.sizes.base) / 2,
},
});
and here is my navigation file
import React from "react";
import { Image } from "react-native";
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import { NavigationContainer } from "#react-navigation/native";
import { createDrawerNavigator } from "#react-navigation/drawer";
import Welcome from "../screens/Welcome";
import Login from "../screens/Login";
import SignUp from "../screens/SignUp";
import Forgot from "../screens/Forgot";
import Explore from "../screens/Explore";
// import Explore1 from "../screens/Explore1";
// import Explore2 from "../screens/Explore2";
// import Explore3 from "../screens/Explore3";
// import Explore4 from "../screens/Explore4";
// import Explore5 from "../screens/Explore5";
// import Explore6 from "../screens/Explore6";
// import Explore7 from "../screens/Explore7";
// import Explore8 from "../screens/Explore8";
import Browse from "../screens/Browse";
import Product from "../screens/Product";
//import Settings from "../screens/Settings";
import Drawer from "../screens/Drawer";
import MarketVisit from "../screens/MarketVisit";
import { theme } from "../constants";
const screens = createStackNavigator(
{
Welcome,
Login,
SignUp,
Forgot,
Explore,
Drawer,
//Browse,
//Product,
//Settings,
MarketVisit,
// NotificationsScreen,
// App,
},
{
defaultNavigationOptions: {
headerStyle: {
height: theme.sizes.base * 4,
backgroundColor: theme.colors.white, // or 'white
borderBottomColor: "transparent",
elevation: 0 // for android
},
// headerBackImage: <Image source={require("../assets/2.jpg")} />,
headerBackTitle: null,
headerLeftContainerStyle: {
alignItems: "center",
marginLeft: theme.sizes.base * 2,
paddingRight: theme.sizes.base
},
headerRightContainerStyle: {
alignItems: "center",
paddingRight: theme.sizes.base
}
}
}
);
export default createAppContainer(screens);

Related

AsyncStorage doesn't save onboarding when closing react native app

Well, I made a presentation onboarding screen, as soon as the user opens the app, the screen is shown, but I want this to be saved using AsyncStorage, if I close and open the app, the onboarding screen is not shown, but the screen of login.
I did all the code but nothing happens and the screen is displayed every time I close and open the app, I don't know what I'm doing wrong, code below.
App.js
import React, { useEffect, useState } from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import {AuthProvider} from './src/providers/Auth';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { OnBoarding } from './src/screen/OnBoarding';
import { SignIn } from './src/screen/SignIn';
import { HomeScreen } from './src/screen/HomeScreen';
import { ActivityIndicator } from 'react-native';
const Stack = createNativeStackNavigator();
const Loading = () => {
return (
<View>
<ActivityIndicator size="large" />
</View>
);
}
export function App(){
const [loading, setLoading] = useState(true);
const [viewedOnboarding, setViewedOnboarding] = useState(false);
useEffect(() => {
checkOnBoarding();
}, [])
const checkOnBoarding = async () => {
try{
const value = await AsyncStorage.getItem('#viewedOnboarding');
if(value !== null){
setViewedOnboarding(true);
}
console.log(value);
}catch(err) {
console.log('Error #checkOnboarding: ', err);
}finally {
setLoading(false)
}
}
return (
<AuthProvider>
<NavigationContainer>
<Stack.Navigator
initialRouteName={loading ? <Loading /> : viewedOnboarding ? <HomeScreen /> : <OnBoarding />}
screenOptions={
{headerShown: false}
}
>
<Stack.Screen
name="SignIn"
component={SignIn}
/>
</Stack.Navigator>
</NavigationContainer>
</AuthProvider>
);
}
Onboarding.js
import React, { useEffect, useState } from 'react';
import {Text, View, StyleSheet, Image, TouchableOpacity, Button} from 'react-native';
import AppIntroSlider from 'react-native-app-intro-slider';
import Icon from 'react-native-vector-icons/FontAwesome';
import AsyncStorage from '#react-native-async-storage/async-storage';
const slides = [
{
key: 1,
title: 'Only Books Can Help You',
text: 'Books can help you to increase your knowledge and become more successfully.',
image: require('../../assets/imagem1.png'),
},
{
key: 2,
title: 'Learn Smartly',
text: 'It’s 2022 and it’s time to learn every quickly and smartly. All books are storage in cloud and you can access all of them from your laptop or PC.',
image: require('../../assets/imagem2.png'),
},
{
key: 3,
title: 'Learn Smartly',
text: 'It’s 2022 and it’s time to learn every quickly and smartly. All books are storage in cloud and you can access all of them from your laptop or PC.',
image: require('../../assets/imagem2.png'),
},
];
export function OnBoarding(){
function renderItem({item}){
return (
<View style={styles.container}>
<Image style={styles.image} source={item.image} />
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.content}>{item.text}</Text>
</View>
);
}
function _renderPrevButton() {
return (
<View style={styles.buttonCircle}>
<Icon
name="angle-left"
color="#000"
size={40}
/>
</View>
);
};
function _renderNextButton() {
return (
<View style={styles.buttonCircle}>
<Icon
name="angle-right"
color="#000"
size={40}
/>
</View>
);
};
const onPressFinish = async () => {
try{
await AsyncStorage.setItem('#viewedOnboarding', 'true')
navigation.navigate('SignIn');
}catch(err) {
console.log("Error #setitem ", err);
}
};
const renderDoneButton = () => {
return (
<TouchableOpacity onPress={onPressFinish}>
<Text style={{color: "#000"}}>Done</Text>
</TouchableOpacity>
);
};
return (
<AppIntroSlider
data={slides}
renderItem={renderItem}
keyExtractor={item => item.key}
renderPrevButton={_renderPrevButton}
renderNextButton={_renderNextButton}
renderDoneButton={renderDoneButton}
showPrevButton
showDoneButton
dotStyle={{backgroundColor: '#9D9D9D'}}
activeDotStyle={{backgroundColor: '#DE7773'}}
/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: "#fff"
},
title: {
color: "#292B38",
fontSize: 24,
fontWeight: 'bold',
marginTop: 50
},
content: {
color: "#4D506C",
textAlign: 'center',
padding: 25,
lineHeight: 18
},
image: {
width: 300,
height: 300,
},
button: {
color: "#000",
backgroundColor: "transparent"
}
})
Probably because of the async nature of AsyncStore when you open your app first you init viewedOnboarding with false, then start reading storage and then you check is onboarding done or not. And of course because storage is async first time you check in Navigation condition you always get
I have modified your checkOnBoarding function.
Here is the code:
const checkOnBoarding = () => {
try{
AsyncStorage.getItem('#viewedOnboarding').then(value => {
if(value !== null){
setViewedOnboarding(true);
}
console.log(value);
})
}catch(err) {
console.log('Error #checkOnboarding: ', err);
}finally {
setLoading(false)
}
}

React native: can't configure the header with navigationOptions

I am new to react-native. I am trying to configure header styles for my app, but it's not working
App.js
import { StatusBar } from 'expo-status-bar';
import React, {useState} from 'react';
import { StyleSheet, Text, View } from 'react-native';
import MealNavigator from './navigation/MealsNavigator';
export default function App() {
return (
<MealNavigator />
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
The following js file i am using for navigation
MealsNavigator.js
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from "react-navigation";
import categoriesScreen from '../screens/categoriesScreen';
import categoryMealScreen from '../screens/categoryMealScreen';
import mealDetailScreen from '../screens/mealDetailScreen';
const MealNavigator = createStackNavigator({
Categories : categoriesScreen,
CategoryMeals : categoryMealScreen,
MealDetail : mealDetailScreen
});
export default createAppContainer(MealNavigator);
The following is the screen where i am trying to configure the header
categoriesScreen.js
import React from 'react';
import {Text,View,Button,FlatList,StyleSheet,TouchableOpacity, Platform} from 'react-native';
import { CATEGORIES } from '../data/dummydata';
const CategoriesScreen = props => {
const renderGrid=(itemData) =>{
return(
<TouchableOpacity style={styles.gridItem} onPress={() =>{props.navigation.navigate({routeName:'CategoryMeals'});}}>
<View>
<Text>{itemData.item.title}</Text>
</View>
</TouchableOpacity>
)
};
return(
<View style={styles.container}>
<FlatList
data={CATEGORIES} renderItem={renderGrid} numColumns={2} />
</View>
);
}
CategoriesScreen.defaultNavigationOptions = ({ navigation }) =>({
title:'Meal Categories',
headerTitleStyle: {
textAlign: "left",
fontSize: 24
},
});
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center'
},
gridItem:{
flexGrow:1,
padding: 20,
margin: 15,
height: 150,
}
});
export default CategoriesScreen;
The following is the dummy data i am using
dummydata.js
import Category from '../models/category';
export const CATEGORIES = [
new Category('c1','Indian','#f5428d'),
new Category('c2','Chinese','#f54242'),
new Category('c3','Thai','#f5a442'),
new Category('c4','Malaysian','#f5d142'),
new Category('c5','Arabian','#368dff'),
new Category('c6','South Indian','#41d95d'),
new Category('c7','Kerala','#9eecff'),
new Category('c8','Bengali','#b9ffb0'),
new Category('c9','Mexican','#ffc7ff'),
new Category('c10','Italian','#47fced'),
];
Following is category class file
category.js
class Category{
constructor(id,title,color){
this.id = id;
this.title = title;
this.color = color;
}
};
export default Category;
Everything else is working, just the header configuration is not working.I am using react navigation version 4
you can cofigure header using navigation.setOptions like this:
import React from 'react';
import {Text,View,Button,FlatList,StyleSheet,TouchableOpacity, Platform} from 'react-native';
import { CATEGORIES } from '../data/dummydata';
const CategoriesScreen = props => {
React.useLayoutEffect(() => {
props.navigation.setOptions({
headerTitle: 'Meal Categories',
headerTitleStyle: {
textAlign: "left",
fontSize: 24
},
});
},
const renderGrid=(itemData) =>{
return(
<TouchableOpacity style={styles.gridItem} onPress={() =>{props.navigation.navigate({routeName:'CategoryMeals'});}}>
<View>
<Text>{itemData.item.title}</Text>
</View>
</TouchableOpacity>
)
};
return(
<View style={styles.container}>
<FlatList
data={CATEGORIES} renderItem={renderGrid} numColumns={2} />
</View>
);
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center'
},
gridItem:{
flexGrow:1,
padding: 20,
margin: 15,
height: 150,
}
});
export default CategoriesScreen;
I found a different solution to my problem. I used defaultNavigationOptions in my navigation file.
MealsNavigator.js
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from "react-navigation";
import categoriesScreen from '../screens/categoriesScreen';
import categoryMealScreen from '../screens/categoryMealScreen';
import mealDetailScreen from '../screens/mealDetailScreen';
import {Platform} from 'react-native';
import colors from '../constants/colors';
const MealNavigator = createStackNavigator({
Categories : {
screen : categoriesScreen,
navigationOptions : {
headerTitle:'Meal Categories',
}
},
CategoryMeals : {
screen : categoryMealScreen
},
MealDetail : mealDetailScreen
},
{
defaultNavigationOptions:{
headerTitleStyle:{
backgroundColor:Platform.OS==='android' ? colors.primaryColor : 'white'
},
headerTintColor:Platform.OS==='android' ? 'white' : colors.primaryColor
}
}
);
export default createAppContainer(MealNavigator);
Thanks to everybody for your help.

The component for route '' must be a React Component

I'm new to react-native and am trying to use the Redux framework, I've encountered this problem: (The component for route ' ' must be a React component):
Thank you in advance.
Screen Error
Index.js
import React from 'react'
import { Provider } from 'react-redux'
import { AppRegistry } from 'react-native';
import { name as appName } from './app.json';
import Menu from './app/componnts/Menu'
import storeConfig from './app/store/storeConfig'
const store = storeConfig()
const Redux = () => {
return (
<Provider store={store}>
<Menu />
</Provider>
)
}
AppRegistry.registerComponent(appName, () => Redux);
Menu.js
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
ScrollView,
Dimensions,
View,
Image,
Text
} from 'react-native'
import { createDrawerNavigator, DrawerItems, } from 'react-navigation'
import Login from './Login/Login'
import Viatura from './Viatura/Viatura'
export default class App extends Component {
render() {
return (
<AppDrawerNavigator />
)
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator({
Login,
Viatura,
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
})
Login.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { loginStore } from '../../store/actions/user.js';
import { Text, View, ImageBackground, Dimensions, Image, TextInput, TouchableOpacity, Alert } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import axios from 'axios'
import { createIconSetFromIcoMoon } from 'react-native-vector-icons'
import { API_MOTORISTAS_LOGIN } from '../../config'
import icoMoonConfig from '../../resources/fonts/selection.json'
import styles from './styles'
import bgImage from '../../images/fundo-vertical-preto.jpg'
import logo from '../../images/logo-tg-v-01.png'
const MyIcon = createIconSetFromIcoMoon(icoMoonConfig, 'icomoon', 'icomoon.ttf');
class Login extends Component {
constructor(props) {
super(props)
this.state = {
user: '',
password: '',
}
this.loginUser = this.loginUser.bind(this)
}
loginUser = () => {
try {
const { user, password } = this.state
this.setState({ error: '', })
axios.post(`${API_MOTORISTAS_LOGIN}`,
{
'param1': this.state.user,
'param2': this.state.password
}, {
"headers": {
'Content-Type': 'application/json',
}
}).then((response) => {
if (response.data.error) {
Alert.alert((response.data.error));
} else {
this.props.onLogin({ ...this.state })
const api_token = response.data.api_token
this.props.navigation.navigate('Viatura', {
api_token: api_token,
})
}
})
.catch((error) => {
console.log("axios error:", error);
});
} catch (err) {
Alert.alert((err))
}
}
static navigationOptions = {
drawerIcon: ({ tintColor }) => (
<MyIcon name="fonte-tg-33" style={{ fontSize: 24, color: tintColor }} />
)
}
render() {
return (
<ImageBackground
source={bgImage}
style={styles.backgroundContainer}>
<View
style={{
height: (Dimensions.get('window').height / 10) * 10,
alignItems: 'center',
justifyContent: 'center',
}}>
<View style={styles.logoContainer}>
<Image source={logo} style={styles.logo} />
</View>
<View style={styles.inputText}>
<View style={styles.iconContainer}>
<MyIcon style={styles.icon} name="fonte-tg-39" size={25} />
</View>
<TextInput
style={styles.input}
placeholder={'User'}
placeholderTextColor={'rgba(0, 0, 0, 0.6)'}
underlineColorAndroid='transparent'
value={this.state.user}
onChangeText={user => this.setState({ user })}
/>
</View>
<View style={styles.inputText}>
<View style={styles.iconContainer}>
<MyIcon style={styles.icon} name="fonte-tg-73" size={25} />
</View>
<TextInput
style={styles.input}
placeholder={'Password'}
secureTextEntry={true}
placeholderTextColor={'rgba(0, 0, 0, 0.6)'}
underlineColorAndroid='transparent'
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</View>
<View style={styles.buttonsLogin}>
<TouchableOpacity style={styles.btnSair}>
<Text style={styles.text}> Sair </Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.loginUser} style={styles.btnEntrar}>
<Text style={styles.text}> Entrar </Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
)
}
}
const mapDispatchToProps = dispatch => {
return {
onLogin: user => dispatch(loginStore(user))
}
}
export default connect(null, mapDispatchToProps)(Login);
actionTypes.js
export const USER_LOGGED_IN = 'USER_LOGGED_IN';
export const USER_LOGGED_OUT = 'USER_LOGGED_OUT';
user.js (inside actions folder)
import { USER_LOGGED_IN, USER_LOGGED_OUT } from './actionTypes'
export const login = user => {
return {
type: USER_LOGGED_IN,
payload: user
}
}
export const logout = () => {
return {
type: USER_LOGGED_OUT,
}
}
user.js (inside reducers folder)
import { USER_LOGGED_IN, USER_LOGGED_OUT } from '../actions/actionTypes'
const initalState = {
user: null,
password: null
}
const reducer = (state = initalState, action) => {
switch (action.type) {
case USER_LOGGED_IN:
return {
...state,
user: action.paypload.user,
password: action.paypload.password
}
case USER_LOGGED_OUT:
return {
...state,
user: null,
password: null,
}
default:
return state
}
}
export default reducer
storeConfig.js
import { createStore, combineReducers } from 'redux'
import userReducer from './reducers/user'
const reducers = combineReducers({
user: userReducer,
})
const storeConfig = () => {
return createStore(reducers)
}
export default storeConfig
As I said at the beginning of the post, I'm still a beginner at react-native, so I'm posting several snippets of code so that I can be as clear as possible about how my situation is.
I don't think your screen is properly setting export default.
can you change this code?
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
ScrollView,
Dimensions,
View,
Image,
Text
} from 'react-native'
import { createDrawerNavigator, DrawerItems, } from 'react-navigation'
import Login from './Login/Login'
import Viatura from './Viatura/Viatura'
export default class App extends Component {
render() {
return (
<AppDrawerNavigator />
)
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator(
{
Login : () => <Login />,
Viatura : () => <Viatura />
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
}
)
OR
import { Login } from './Login/Login'
import { Viatura } from './Viatura/Viatura'
...
const AppDrawerNavigator = createDrawerNavigator(
{
Login : { screen: Login },
Viatura : { screen: Viatura }
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
}
)
Try this
const AppDrawerNavigator = createDrawerNavigator({
Login:Login,
Viatura:Login,
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
})

Unable to connect mapStateToProps and mapDispatchToProps

I'm getting an error that undefined is not a function(evaluating 'this.props.addTodo(text)')
my code was working fine before i introduces the react-navigation as after that i want to add a todo from my second screen i.e. Counter and want to see whether the list on screen one gets updated or not. but i got stuck at adding a todo on first screen as it is throwing the above error.
I'm a complete begginner in React-native and Redux and also in Js. Btw thanks and in advance
and here is my code:
App.js
import React from 'react';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import TodoApp from './src/TodoApp'
import store from './app/store/index'
import { Provider } from 'react-redux'
import {CounterR} from './app/counterR';
import {Counter} from './app/counter';
import {createStackNavigator, createAppContainer} from 'react-
navigation'
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppContainer />
</Provider>
);
}
}
const stack = createStackNavigator({
Home: CounterR,
Second: Counter
},{
initialRouteName: 'Home'
})
const AppContainer = createAppContainer(stack)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
CounterR.js
import React, { Component } from 'react';
import {View,
TouchableOpacity,
Text,
Dimensions,
StyleSheet,
TextInput,
FlatList,
Keyboard} from 'react-native';
import {connect} from 'react-redux'
import { addTodo } from './actions/index'
import { toggleTodo } from './actions/index'
import {NavigationAction} from 'react-navigation'
import store from './store/index'
import { Provider } from 'react-redux'
const { width, height } = Dimensions.get("window");
export class CounterR extends Component{
state = {
text: ""
}
add = text => {
Keyboard.dismiss()
this.props.addTodo(text)
this.setState({text: ""})
}
render(){
return(
<View style={styles.container}>
<TextInput
style={{borderWidth:.5, width: 300, height: 40}}
defaultValue={this.state.text}
onChangeText={(value) => this.setState({text:value})}/>
<TouchableOpacity
onPress={() => this.add(this.state.text)}>
<Text
style={{fontSize: 18}}>ADD TODO</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Second')}>
<Text
style={{fontSize: 18}}>Second Screen</Text>
</TouchableOpacity>
<FlatList
data= {this.props.todos}
numColumns={1}
keyExtractor= {item => item.id}
renderItem ={({ item }) =>
<TouchableOpacity
onPress={() => this.props.toggleTodo(item)}
style={styles.todoText}>
<Text style={{textDecorationLine: item.completed ? 'line-through' : 'none', fontSize: 20}}>{item.text}</Text>
</TouchableOpacity>
}
/>
</View>
)
}
}
const mapStateToProps = state => ({
todos: state.todos
})
const mapDispatchToProps = dispatch => ({
addTodo: text => dispatch(addTodo(text)),
toggleTodo: item => dispatch(toggleTodo(item))
})
export default connect(mapStateToProps, mapDispatchToProps)(CounterR)
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,
},
todoText: {
width: width,
margin: 10
}
});
Counter.js
import React, { Component } from 'react';
import {View,
TouchableOpacity,
Text,
Dimensions,
StyleSheet,
TextInput,
FlatList,
Keyboard} from 'react-native';
import {connect} from 'react-redux'
import { addTodo } from './actions/index'
import { toggleTodo } from './actions/index'
import { Provider } from 'react-redux'
import store from './store/index'
const { width, height } = Dimensions.get("window");
export class Counter extends Component{
state = {
text: "",
}
addTodo = text => {
Keyboard.dismiss()
this.props.addTodo(text)
this.setState({text: ""})
}
render(){
return(
<View style={styles.container}>
<TextInput
style={{borderWidth:.5, width: 300, height: 40}}
defaultValue={this.state.text}
onChangeText={(value) => this.setState({text: value})}/>
<TouchableOpacity
onPress={() => this.addTodo(this.state.text)}>
<Text
style={{fontSize: 18}}>ADD TODO</Text>
</TouchableOpacity>
</View>
)
}
}
const mapStateToProps = state => ({
todos: state.todos
})
const mapDispatchToProps = dispatch => ({
addTodo: text => dispatch(addTodo(text)),
toggleTodo: item => dispatch(toggleTodo(item))
})
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
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,
},
todoText: {
width: width,
margin: 10
}
});
app/actions/index.js
import {Keyboard} from 'react-native'
import { ADD_TODO, TOGGLE_TODO } from './actionTypes'
let x = 0
export const addTodo = (text) => ({
type: ADD_TODO,
id: x++,
text: text
})
export const toggleTodo = (item) => ({
type: TOGGLE_TODO,
id: item.id
})
app/actions/actionTypes.js
export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
app/reducers/index.js
import { combineReducers } from 'redux'
import todos from './todos'
export default combineReducers({
todos
})
app/reducers/todos.js
const todos = (state =[], action) => {
switch(action.type){
case 'ADD_TODO':
return [
...state, {
id: action.id,
text: action.text,
completed: false
}
]
case 'TOGGLE_TODO':
return state.map(todo =>
(todo.id === action.id)
?
{...todo, completed: !todo.completed}
:
todo)
default:
return state
}
}
export default todos
app/store/index.js
import { createStore } from 'redux'
import rootReducer from '../reducers'
export default store = createStore(rootReducer)

React Navigation Issue with NavigationActions

I have an application in which I am trying to apply navigation in some case. For example, A, B, C, D are my tabs and in the tab A, I have 3 pages as 1, 2, 3. Now in a situation where I am on tab A and on page 3, there is one button present in which I have to navigate back to page 1 on the same tab itself (A).
But somehow, my navigation is not working in this case. Below are my codes:
SkippedTask.js
import React from "react";
import {
View,
StyleSheet,
Text,
AsyncStorage,
Dimensions,
Image,
ScrollView,
Alert
} from "react-native";
import ButtonC from "../../components/ButtonC";
import { NavigationActions } from "react-navigation";
import Server from "../../provider/Server";
var { width, height } = Dimensions.get("window");
export default class SkippedTask extends React.Component {
constructor(props) {
super(props);
this.state = {
loadingState: false,
api: new Server(),
mobile: "",
arrayLenght: "",
tasklist: [],
taskTitle: []
};
}
renderSkippedQues() {
return (
<View style={{ marginTop: 0 }}>
{this.state.taskTitle.map((item, key) => (
<View key={key} style={{ marginTop: 0 }}>
<Text style={{}}>
<Text style={{ fontSize: 18, color: "#000" }}>{"\u2022"} </Text>{" "}
{item}
</Text>
</View>
))}
</View>
);
}
handleNav = () => {
this.props.navigation.dispatch(
NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: "DashboardTab" })]
})
);
};
render() {
if (this.state.arrayLenght <= 0) {
return <View />;
} else {
return (
<ScrollView>
<View
style={{
justifyContent: "center",
alignItems: "center",
marginTop: height / 40
}}
>
<Text style={{ fontSize: 16, color: "black", marginTop: 30 }}>
List of skipped task are :
</Text>
{this.renderSkippedQues()}
<View style={{ marginTop: 40 }} />
<ButtonC
title=" Click here to complete remaining task "
onPress={this.handleNav}
/>
</View>
</ScrollView>
);
}
}
}
Below is my App.js file in which I am using StackNavigator of react-navigation.
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import { AppRegistry } from 'react-native';
import { StackNavigator } from 'react-navigation';
import SessionCheck from './src/screens/SessionCheck';
import LoginScreen from './src/screens/LoginScreen';
import RegisterScreen from './src/screens/RegisterScreen';
import ProfileScreen from './src/screens/ProfileScreen';
import WalletsScreen from './src/screens/WalletsScreen';
import DashboardAccept from './src/screens/DashboardAccept';
import TermsConditionsScreen from './src/screens/TermsConditionsScreen';
import DashboardTabScreen from './src/screens/DashboardTabScreen';
import Person from './src/components/profile/Person';
import Payment from './src/components/profile/Payment';
import List from './src/components/task/List';
const App = StackNavigator({
// DashboardTab: { screen:DashboardTabScreen },
Home: { screen: SessionCheck },
Login: { screen: LoginScreen },
Register: { screen: RegisterScreen },
Profile: { screen:ProfileScreen },
Wallets: { screen:WalletsScreen },
DashboardAccept: { screen:DashboardAccept },
TermsConditions: { screen:TermsConditionsScreen },
DashboardTab: { screen:DashboardTabScreen },
Person: {screen: Person},
Payment : {screen: Payment},
AllTask:{screen: List}
});
export default App;
Now my case lies that I need to navigate from the SkippedTask page to AllTask screen as mentioned in the App.js file. But somehow I am not able to resolve this issue.
Any leads are appreciated. Thanks.