React navigation 6.x not passing props - reactjs

I have the code as below, every time i try to pass parameter from Home Page to the Second Page i keep getting undefined, and i never got the props or anything.
This is my app.js file
import React from 'react';
import {
SafeAreaView,
StatusBar,
Text,
View,
} from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import Home from './App/screens/home';
import Second from './App/screens/second';
function HomeScreen() {
return (
<Home />
);
}
function OtherScreen() {
return (
<Second />
);
}
const Stack = createNativeStackNavigator();
const App = () => {
return (
<SafeAreaView style={{ flex: 1 }}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'Overview' }} />
<Stack.Screen
name="Second"
component={OtherScreen}
/>
</Stack.Navigator>
</NavigationContainer>
</SafeAreaView>
);
};
export default App;
This is Home Page
import React, { useState } from 'react';
import {
Button,
Dimensions,
Platform,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { useNavigation } from '#react-navigation/native';
const Home = () => {
const isDarkMode = useColorScheme() === 'dark';
const navigation = useNavigation();
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<View
style={{
backgroundColor: isDarkMode ? Colors.black : Colors.white,
}}>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Second', { name: "John Doe" })}
/>
<LearnMoreLinks />
</View>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
},
highlight: {
fontWeight: '700',
},
});
export default Home;
This is the screen named "Second"
import React, { useEffect } from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
useColorScheme,
} from 'react-native';
import {
Colors,
Header,
} from 'react-native/Libraries/NewAppScreen';
import { useNavigation } from '#react-navigation/native';
const Second = ({ route }) => {
const isDarkMode = useColorScheme() === 'dark';
const navigation = useNavigation();
useEffect(() => {
console.log(route)
})
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
},
highlight: {
fontWeight: '700',
},
});
export default Second;
i have tried a lot of solutions before i post this question most of them is version 4.x or 5.x

You don't need to declare a function to return the screen, just assign to component directly:
const App = () => {
return (
<SafeAreaView style={{ flex: 1 }}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen
name="Home"
component={Home}
options={{ title: 'Overview' }} />
<Stack.Screen
name="Second"
component={Second}
/>
</Stack.Navigator>
</NavigationContainer>
</SafeAreaView>
);
};

Related

Navigate to another page in React Native

I have difficulty navigate to another page. I want to click Card in Profile page and then it will navigate to page CardHome. I add <NavigationContainer> in apps.js but didnt work. I am newbie so I am not sure where is wrong. Hopefully someone can help me.
This is profile.js
`import React, { useState, useEffect } from 'react'import { Text, View, StyleSheet, SafeAreaView, TouchableOpacity } from 'react-native'
import { firebase } from '../config'import EntypoIcon from "react-native-vector-icons/Entypo";
import { createStackNavigator } from '#react-navigation/stack';import { NavigationContainer } from '#react-navigation/native';import CardHome from '../CardHome';
const Profile = () => {const [name, setName] = useState('')
useEffect (() => {
firebase.firestore().collection('users')
.doc(firebase.auth().currentUser.uid).get()
.then((snapshot) => {
if(snapshot.exists){
setName(snapshot.data())
}
else {
console.log('User does not exist')
}
})
}, [])
return (
<SafeAreaView style={styles.container}>
<Text style={{fontSize:20, fontWeight:'bold', marginLeft:180, marginBottom:-11}}>
{name.username}
</Text>
<TouchableOpacity
onPress={() => navigation.navigate('CardHome')}
style={styles.button3}>
<View style={styles.icon3Row}>
<EntypoIcon name="open-book" style={styles.icon3}></EntypoIcon>
<Text style={styles.card}>CARD</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {firebase.auth().signOut()}}
style={styles.button5}>
<EntypoIcon name="user" style={styles.icon5}></EntypoIcon>
</TouchableOpacity>
</SafeAreaView>
)
}`
This is my CardHome.js
`import React, { Component } from "react";
import { StyleSheet, View, TouchableOpacity, Text } from "react-native";
import EntypoIcon from "react-native-vector-icons/Entypo";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
function CardHome(props) {
return (
<View style={styles.container}>
<View style={styles.buttonRow}>
<TouchableOpacity style={styles.button}>
<Text style={styles.scam}>SCAM</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button5}>
<EntypoIcon name="magnifying-glass" style={styles.icon5}></EntypoIcon>
<Text style={styles.explore3}>EXPLORE</Text>
</TouchableOpacity>
</View>
<View style={styles.button4Row}>
<TouchableOpacity style={styles.button4}>
<Text style={styles.socialEngineering}>SOCIAL ENGINEERING</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button3}>
<EntypoIcon name="magnifying-glass" style={styles.icon4}></EntypoIcon>
<Text style={styles.explore2}>EXPLORE</Text>
</TouchableOpacity>
</View>
</View>
);
}
this is my Apps.js
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import React, { useState, useEffect } from 'react';
import { firebase } from './config';
import Login from "./src/Login";
import Registration from "./src/Registration";
import Profile from "./src/Profile";
import Header from "./components/Header";
import CardHome from "./CardHome";
const Stack = createStackNavigator();
function App() {
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
function onAuthStateChanged(user) {
setUser(user);
if (initializing) setInitializing(false);
}
useEffect(() => {
const subscriber = firebase.auth().onAuthStateChanged(onAuthStateChanged);
return subscriber;
}, []);
if (initializing) return null;
if (!user) {
return (
<Stack.Navigator>
<Stack.Screen
name="Login"
component={Login}
options={{
headerTitle: () => <Header name="MySecureAwareness" />,
headerStyle: {
height: 150,
borderBottomLeftRadius: 50,
borderBottomRightRadius: 50,
backgroundColor: "#00e4d0",
shadowColor: "#000",
elevation: 25,
}
}}
/>
<Stack.Screen
name="Registration"
component={Registration}
options={{
headerTitle: () => <Header name="MySecureAwareness" />,
headerStyle: {
height: 150,
borderBottomLeftRadius: 50,
borderBottomRightRadius: 50,
backgroundColor: "#00e4d0",
shadowColor: "#000",
elevation: 25
}
}}
/>
</Stack.Navigator>
);
}
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Profile"
component={Profile}
options={{
headerTitle: () => <Header name="MySecureAwareness" />,
headerStyle: {
height: 150,
borderBottomLeftRadius: 50,
borderBottomRightRadius: 50,
backgroundColor: "#00e4d0",
shadowColor: "#000",
elevation: 25
}
}}
/>
<Stack.Screen
name="CardHome" component={CardHome} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default () => {
return (
<NavigationContainer>
<App />
</NavigationContainer>
)
}
I want to click Card then it will navigate to Cardhome.js.

React Navigation. How to navigate with class component?

I am trying to navigate with React Navigate.
When clicking on the image I get this error in console:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
I have tried different methods to navigate, but without success. Any suggestions?
This is my code:
import React, { Component } from 'react';
import { StyleSheet, Text, View, SafeAreaView, Image, TouchableHighlight } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { useNavigation } from '#react-navigation/native';
const Stack = createNativeStackNavigator();
import Home from './screens/homeScreen';
import Teams from './screens/teamsScreen';
export default class App extends Component {
GoTo({ screenName }) {
const navigation = useNavigation();
navigation.navigate(screenName);
}
render() {
return (
<SafeAreaView style={{flex: 1,}}>
<View style={styles.header}>
<TouchableHighlight onPress={() => this.GoTo('Teams')}>
<Image
style={styles.headerLogo}
source={{uri: 'https://yukigassen.no/uploads/Yukigassen_Logo_Big_Transparent.png'}}
resizeMode={'stretch'}
/>
</TouchableHighlight>
<View style={styles.headerRight}>
<Image
style={{width: 25, height: 25}}
source={{uri: 'https://icons.iconarchive.com/icons/dtafalonso/android-lollipop/512/Settings-icon.png'}}
/>
</View>
</View>
<View style={styles.screen}>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} options={{headerShown: false}} />
<Stack.Screen name="Teams" component={Teams} options={{headerShown: false}} />
</Stack.Navigator>
</NavigationContainer>
</View>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
header: {
height: '7.5%',
padding: 5,
},
headerLogo: {
width: 160,
height: 50,
marginLeft: 10,
},
headerRight:{
position: 'absolute',
right: 5,
top: 15,
},
screen: {
flex: 1,
},
});
useNavigation() is a hook that cannot be used with class components but there is a way around it. You can create a wrapper component and pass the navigation prop into your class component.
class App extends Component {
render() {
// Get it from props
const { navigation } = this.props;
...
}
}
// Wrap and export
export default function(props) {
const navigation = useNavigation();
return <App {...props} navigation={navigation} />;
}
Example from https://reactnavigation.org/docs/use-navigation/
you can try this approach, make that comp default route and check, lemme know if this helps :) thanks
import React, { Component } from 'react';
import { StyleSheet, Text, View, SafeAreaView, Image, TouchableHighlight } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { useNavigation } from '#react-navigation/native';
const Stack = createNativeStackNavigator();
import Home from './screens/homeScreen';
import Teams from './screens/teamsScreen';
const DefaultRoute = () => {
GoTo({ screenName }) {
const navigation = useNavigation();
navigation.navigate(screenName);
}
return(
<SafeAreaView style={{flex: 1,}}>
<View style={styles.header}>
<TouchableHighlight onPress={() => this.GoTo('Teams')}>
<Image
style={styles.headerLogo}
source={{uri: 'https://yukigassen.no/uploads/Yukigassen_Logo_Big_Transparent.png'}}
resizeMode={'stretch'}
/>
</TouchableHighlight>
<View style={styles.headerRight}>
<Image
style={{width: 25, height: 25}}
source={{uri: 'https://icons.iconarchive.com/icons/dtafalonso/android-lollipop/512/Settings-icon.png'}}
/>
</View>
</View>
</SafeAreaView>
)
}
export default class App extends Component {
render() {
return (
<SafeAreaView style={styles.screen}>
<NavigationContainer>
<Stack.Navigator initialRouteName="DefaultRoute">
<Stack.Screen name="DefaultRoute" component={DefaultRoute} options={{headerShown: false}} />
<Stack.Screen name="Home" component={Home} options={{headerShown: false}} />
<Stack.Screen name="Teams" component={Teams} options={{headerShown: false}} />
</Stack.Navigator>
</NavigationContainer>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
header: {
height: '7.5%',
padding: 5,
},
headerLogo: {
width: 160,
height: 50,
marginLeft: 10,
},
headerRight:{
position: 'absolute',
right: 5,
top: 15,
},
screen: {
flex: 1,
},
});

The action 'NAVIGATE' with payload was not handled by any navigator [React Native]

Hello I have 3 drawer Navigators[Home,List,Contact] and I want to navigate from List Screen to an other Screen called EditScreen this Why I create a Stack Navigator on the List Screen But I got an error when I press the name on the table thet should take me to From the List Screen to The Edit Screen.
App.js
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { createDrawerNavigator } from '#react-navigation/drawer';
import COLORS from './src/conts/colors';
import HomeScreen from './Screens/HomeScreen';
import ListScreen from './Screens/ListScreen';
import FormScreen from './Screens/FormScreen';
import EditScreen from './Screens/EditScreen';
const Stack = createNativeStackNavigator();
const Drawer = createDrawerNavigator();
const App = () => {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home" screenOptions={{
headerStyle: {
backgroundColor: COLORS.lightkBlue
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold'
}
}}>
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="List" component={ListScreen} />
<Drawer.Screen name="Form" component={FormScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}
export default App;
ListScreen.js
import React, { useState } from 'react';
import { StyleSheet, SafeAreaView, ScrollView,Text, View, Modal } from 'react-native';
import { DataTable } from 'react-native-paper';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import COLORS from '../src/conts/colors';
import Button from '../src/views/components/Button';
import EditScreen from './EditScreen';
const Stack = createNativeStackNavigator();
function Edit() {
return (
<Stack.Navigator>
<Stack.Screen name="Edit" component={EditScreen} />
</Stack.Navigator>
);
}
const List = ({navigation}) => {
const data = [
{id:1,name:"Hassane1",phone:"068888188888",email:"contact#gemail.com"},
{id:2,name:"Hassane2",phone:"068888888288",email:"contact#gemail.com"},
{id:3,name:"Hassane3",phone:"068888388888",email:"contact#gemail.com"},
]
const renderList = data.map((item)=>{
return(
<DataTable.Row key={item.id}>
<DataTable.Cell onPress={() => navigation.navigate("Edit",{item})} >{item.name}</DataTable.Cell>
<DataTable.Cell>{item.email}</DataTable.Cell>
<DataTable.Cell>{item.phone}</DataTable.Cell>
</DataTable.Row>
)
})
return (
<SafeAreaView style={{backgroundColor: COLORS.white, flex: 1}}>
<ScrollView
contentContainerStyle={{paddingTop: 50, paddingHorizontal: 20}}>
<Text style={{color: COLORS.black, fontSize: 40, fontWeight: 'bold'}}>
List of Companies
</Text>
<Text style={{color: COLORS.grey, fontSize: 18, marginVertical: 10}}>
Check Our Companies Details
</Text>
<DataTable style={styles.container} >
<DataTable.Header style={styles.tableHeader} >
<DataTable.Title>Name</DataTable.Title>
<DataTable.Title>email</DataTable.Title>
<DataTable.Title>Phone</DataTable.Title>
</DataTable.Header>
</DataTable>
{renderList}
</ScrollView>
</SafeAreaView>
);
};
export default List;
const styles = StyleSheet.create({
container: {
padding: 15,
},
tableHeader: {
backgroundColor: '#F3F4FB',
},
modalButtonView: {
}
});
EditScreen.js
import React, { useState } from 'react';
import {
View,
Text,
TextInput,
SafeAreaView,
Keyboard,
ScrollView,
Alert,
} from 'react-native';
import COLORS from '../src/conts/colors';
import Button from '../src/views/components/Button';
import Input from '../src/views/components/Input';
import Loader from '../src/views/components/Loader';
const EditScreen = (props) => {
const {id,name,phone,email} = props.route.params.item
const [inputs, setInputs] = React.useState({
name: '',
email: '',
phone: '',
});
const [errors, setErrors] = React.useState({});
const [loading, setLoading] = React.useState(false);
const validate = () => {
Keyboard.dismiss();
let isValid = true;
if (!inputs.name) {
handleError('Please input Company', 'name');
isValid = false;
}
if (!inputs.email) {
handleError('Please input email', 'email');
isValid = false;
} else if (!inputs.email.match(/\S+#\S+\.\S+/)) {
handleError('Please input a valid email', 'email');
isValid = false;
}
if (!inputs.phone) {
handleError('Please input phone number', 'phone');
isValid = false;
}
{/*if (isValid) {
register();
}*/}
};
const handleOnchange = (text, input) => {
setInputs(prevState => ({...prevState, [input]: text}));
};
const handleError = (error, input) => {
setErrors(prevState => ({...prevState, [input]: error}));
};
return (
<SafeAreaView style={{backgroundColor: COLORS.white, flex: 1}}>
<Loader visible={loading} />
<ScrollView
contentContainerStyle={{paddingTop: 50, paddingHorizontal: 20}}>
<Text style={{color: COLORS.black, fontSize: 40, fontWeight: 'bold'}}>
Edit
</Text>
<Text style={{color: COLORS.grey, fontSize: 18, marginVertical: 10}}>
Now You Can Edit !
</Text>
<View style={{marginVertical: 20}}>
<Input
onChangeText={text => handleOnchange(text, 'name')}
onFocus={() => handleError(null, 'name')}
iconName="account-outline"
label="Company"
placeholder="Enter your Company Name"
error={errors.name}
defaultValue={name}
/>
<Input
onChangeText={text => handleOnchange(text, 'email')}
onFocus={() => handleError(null, 'email')}
iconName="email-outline"
label="Email"
placeholder="Enter your email address"
error={errors.email}
defaultValue={email}
/>
<Input
keyboardType="numeric"
onChangeText={text => handleOnchange(text, 'phone')}
onFocus={() => handleError(null, 'phone')}
iconName="phone-outline"
label="Phone Number"
placeholder="Enter your phone no"
error={errors.phone}
defaultValue={phone}
/>
<Button title="Save" onPress={validate} />
<Button title="Cancel" onPress={() => props.navigation.navigate("List")} />
</View>
</ScrollView>
</SafeAreaView>
);
};
export default EditScreen;
This is The Error
enter image description here
Your 'Edit' navigator is declared in your Edit() function but the function is never called.
react-navigation does know how to navigate to it since it is never initiated
You should try to call the function at least once at component start so the navigator is initiated
You do not have EditScreen as a screen on the drawers navigation screens in App.js
Try to add:
<Drawer.Screen name="Edit" component={EditScreen} />
On App.js

Too much space between the appbar and status bar

I am making an app, where I want to use react navigation.
For some reason, whenever I use drawers in react navigation, there is a huge space between the status bar and the drawer app bar.
Here is my code for the ho -
import { StatusBar } from "expo-status-bar";
import * as React from "react";
import { useState, useEffect } from "react";
import { StyleSheet, Text, View, ScrollView } from "react-native";
import Constants from "expo-constants";
import Header from "../Header";
import { Flexbox } from "../Layout";
import Card from "../Card";
import { marginAboveCard } from "../../constants/constants";
import Row from "../Row";
import { convertToIndianNumberingFormat } from "../../utils/utils";
const HomeScreen = ({ navigation }) => {
const [cardsData, setCardsData] = useState({
confirmed: 0,
active: 0,
recovered: 0,
deceased: 0,
tests: 0,
critical: 0,
});
const [lastUpdated, setLastUpdated] = useState("");
useEffect(() => {
const getData = async () => {
const cardsDataResponse = await fetch(
"https://disease.sh/v3/covid-19/all"
);
const cardsDataFetched = await cardsDataResponse.json();
setCardsData({
confirmed: convertToIndianNumberingFormat(
cardsDataFetched.cases
),
active: convertToIndianNumberingFormat(cardsDataFetched.active),
recovered: convertToIndianNumberingFormat(
cardsDataFetched.recovered
),
deceased: convertToIndianNumberingFormat(
cardsDataFetched.deaths
),
tests: convertToIndianNumberingFormat(cardsDataFetched.tests),
critical: convertToIndianNumberingFormat(
cardsDataFetched.critical
),
});
const time = new Date(cardsDataFetched.updated);
const lastupdated = time.toLocaleTimeString();
setLastUpdated(`Last updated at ${lastupdated}`);
};
getData();
}, []);
return (
<ScrollView style={styles.main}>
<View style={{ marginTop: Constants.statusBarHeight }}>
<StatusBar style="auto" />
<Header text="COVID-19" />
<Text style={styles.lastUpdatedText}>{lastUpdated}</Text>
<View style={{ marginTop: marginAboveCard }}>
<Flexbox style={{ marginTop: 15 }}>
<Card
background="red"
title="Confirmed"
number={cardsData.confirmed}
/>
<Card
background="#3877F0"
title="Active"
number={cardsData.active}
/>
</Flexbox>
<Flexbox style={{ marginTop: marginAboveCard }}>
<Card
background="#47CC3C"
title="Recovered"
number={cardsData.recovered}
/>
<Card
background="#868686"
title="Deceased"
number={cardsData.deceased}
/>
</Flexbox>
<Flexbox style={{ marginTop: marginAboveCard }}>
<Card
background="#E85FEB"
title="Tests"
number={cardsData.tests}
/>
<Card
background="#5BF8B6"
title="Critical"
number={cardsData.critical}
/>
</Flexbox>
</View>
<View style={{ marginTop: 30 }}>
<Header text="TABLE STATISTICS" />
</View>
</View>
</ScrollView>
);
};
export default HomeScreen;
const styles = StyleSheet.create({
main: {
flex: 1,
backgroundColor: "#000232",
},
lastUpdatedText: {
color: "white",
textAlign: "center",
marginTop: 12,
fontSize: 15,
},
});
My app.jsx -
import * as React from "react";
import HomeScreen from "./components/screens/HomeScreen";
import VaccineScreen from "./components/screens/VaccineScreen";
import { NavigationContainer } from "#react-navigation/native";
import { createDrawerNavigator } from "#react-navigation/drawer";
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="Vaccine" component={VaccineScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}
If you look at the code of home screen properly, you would see a status style component which is set to auto. Even after removing it, the space is there. There are no errors in the console of any sort. This error started coming when I used react navigation drawer. Is there a way I can remove the space?
Did you try to move StatusBar as top most child like my sample below?
....
<View>
<StatusBar style="auto" />
<ScrollView style={styles.main}>
<View style={{ marginTop: Constants.statusBarHeight }}>
...
How you define the header title and the drawer icon?

React Native, Redirect from Splash Screen to another screen

I am trying to navigate from SplashScreen to another screen after 5 second and I get this error:
Code from SplashScreen:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,Alert, ImageBackground,Image,AsyncStorage,ActivityIndicator} from 'react-native';
import { StackNavigator } from 'react-navigation';
export default class App extends Component<Props> {
componentDidMount () {
setTimeout(() => {
// this._retrieveData();
this.props.navigation.replace("Journeys");
}, 5000)
}
render() {
return (
<ImageBackground
source={require('../../assets/rsz_blue_bg.png')}
style = {{flex: 1, height: '100%', width: '100%', resizeMode : 'stretch'}}>
<Image
source={require('../../assets/logo_white.png')}
style = {{ width: '100%', height:'70%', marginTop: 100 }}
/>
</ImageBackground>
);
}
}
Code from App.js:
import React, { useContext, useEffect } from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { createDrawerNavigator } from '#react-navigation/drawer';
import Icon from 'react-native-vector-icons/Ionicons';
//I am doing the imports here but I am cutting down the code to be able to post :)
const AuthStack = createStackNavigator()
const AuthStackScreen = () => (
<AuthStack.Navigator screenOptions={{headerShown: false}}>
<AuthStack.Screen name="SignIn" component={SignInScreen} />
<AuthStack.Screen name="SignUp" component={SignUpScreen} />
</AuthStack.Navigator>
)
const FirstStack = createStackNavigator()
const FirstStackScreen = ({navigation}) => (
<FirstStack.Navigator screenOptions={{
headerStyle: {
backgroundColor: '#009387'
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
// alignSelf: 'center',
}
}}>
<FirstStack.Screen
name="Journeys"
component={TrackCreateScreen}
options={{
headerLeft: () => (
<Icon.Button
name="ios-menu"
size={25}
backgroundColor="#009387"
onPress={() => {navigation.openDrawer()}}></Icon.Button>
)
}}
/>
</FirstStack.Navigator>
)
const TrackListStack = createStackNavigator()
const TrackListScreens = ({navigation}) => (
<TrackListStack.Navigator screenOptions={{
headerStyle: {
backgroundColor: '#009387'
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold'
}
}}>
<TrackListStack.Screen
name="History"
component={TrackListScreen}
options={{
headerLeft: () => (
<Icon.Button
name="ios-menu"
size={25}
backgroundColor="#009387"
onPress={() => {navigation.openDrawer()}}></Icon.Button>
)
}}
/>
<TrackListStack.Screen name="Journey Details" component={TrackDetailScreen} />
</TrackListStack.Navigator>
)
const AccountStack = createStackNavigator()
const AccountScreens = ({navigation}) => (
<AccountStack.Navigator screenOptions={{
headerStyle: {
backgroundColor: '#009387'
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold'
}
}}>
<AccountStack.Screen
name="Account"
component={AccountScreen}
options={{
headerLeft: () => (
<Icon.Button
name="ios-menu"
size={25}
backgroundColor="#009387"
onPress={() => {navigation.openDrawer()}}></Icon.Button>
)
}}
/>
</AccountStack.Navigator>
)
const AppStack = createDrawerNavigator()
const AppStackScreen = ({navigation}) => (
<AppStack.Navigator drawerContent={props => <DrawerContent {...props}/>}>
<AppStack.Screen name="Journey" component={FirstStackScreen} />
<AppStack.Screen name="History" component={TrackListScreens} />
<AppStack.Screen name="Account" component={AccountScreens} />
</AppStack.Navigator>
)
const App = () => {
const { state } = useContext(AuthContext)
if(state.isLoading) {
return <LoadingScreen />
}
return (
<NavigationContainer>
<SplashScreen/>
</NavigationContainer>
)
}
export default () => (
<AuthProvider>
<LocationProvider>
<TrackProvider>
<App />
</TrackProvider>
</LocationProvider>
</AuthProvider>
)
Or if you have a better option to do this redirection it's ok anyway.
I tried various methods and for sure I am doing something wrong.
Please help.
this is not accessible in setTimeout.
componentDidMount () {
let self = this;
setTimeout(() => {
// this._retrieveData();
self.props.navigation.replace("Journeys");
}, 5000)
}

Resources