Undefined Error When Trying to Get React Navigation Params - javascript

I'm having an issue. I am getting the error: undefined is not an object (evaluating '_route$params.originPlace').
import { View, Text, Dimensions } from "react-native";
import React from "react";
import HomeMap from "../components/HomeMap/HomeMap";
import RideTypes from "../components/RideTypes/RideTypes";
import styles from "./styles.js";
import RouteMap from "../components/RouteMap/RouteMap";
import { useRoute } from "#react-navigation/native";
import { useNavigation } from "#react-navigation/native";
const SearchResult = (props) => {
const navigation = useNavigation();
const route = useRoute();
console.log(route.params);
const { originPlace, destinationPlace } = route.params;
return (
<View>
<View style={{ height: Dimensions.get("window").height - 400 }}>
<RouteMap origin={originPlace} destination={destinationPlace} />
</View>
<View>
<RideTypes />
</View>
</View>
);
};
export default SearchResult;
Heres the other file where I m taking the origin and destination. But I don't know what is wrong in here. I m not able to figure out. Help!
import { View, Text, Image, FlatList } from "react-native";
import React from "react";
import MapView, { PROVIDER_GOOGLE, Marker } from "react-native-maps";
import cars from "../../../assets/data/cars";
import MapViewDirections from "react-native-maps-directions";
import {GOOGLE_MAPS_APIKEY} from "#env";
const RouteMap = ({origin,destination}) => {
const originLoc = {
latitude: origin.details.geometry.location.lat,
longitude: origin.details.geometry.location.lng,
}
const destinationLoc = {
latitude:destination.details.geometry.location.lat,
longitude:destination.details.geometry.location.lng,
}
console.log(originLoc);
return (
<MapView
style={{ width: "100%", height: "100%" }}
provider={PROVIDER_GOOGLE}
showsUserLocation={true}
initialRegion={{
latitude: 28.450627,
longitude: -16.263045,
latitudeDelta: 0.0222,
longitudeDelta: 0.0421,
}}
>
<MapViewDirections
origin={originLoc}
destination={destinationLoc}
apikey={GOOGLE_MAPS_APIKEY}
strokeWidth={3}
strokeColor="hotpink"
/>
<Marker
coordinate={originLoc}
title={'Origin'}
/>
<Marker
coordinate={destinationLoc}
title={'Destination'}
/>
</MapView>
);
};
export default RouteMap;
And here is the destination Search js file which will redirect to search result once origin and destination selected from google apis.
import { View, Text, TextInput, SafeAreaView } from 'react-native';
import React, { useEffect, useState } from 'react';
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";
import { GOOGLE_MAPS_APIKEY } from "#env";
import { useNavigation } from '#react-navigation/native';
import styles from './styles';
import PlaceRow from './PlaceRow.js';
const DestinationSearch = (props) => {
navigation = useNavigation();
const homePlace = {
description: 'Home',
geometry: { location: { lat: 48.8152937, lng: 2.4597668 } },
};
const workPlace = {
description: 'Work',
geometry: { location: { lat: 48.8496818, lng: 2.2940881 } },
};
const checkNavigation = () => {
if (originPlace && destinationPlace) {
navigation.navigate('SearchResult'), {
originPlace,
destinationPlace,
}
}
}
const [originPlace, setOriginPlace] = useState( null ) ;
const [destinationPlace, setDestinationPlace] = useState( null );
useEffect(() =>{
checkNavigation();
}, [originPlace,destinationPlace]);
return (
<SafeAreaView>
<View style= {styles.container}>
{/* From */}
<GooglePlacesAutocomplete
backgroundColor= "#eee"
nearbyPlacesAPI="GooglePlacesSearch"
placeholder="From"
styles={{
textInput: styles.textInput,
container: styles.autoCompleteContainer,
listView: styles.listView,
separator: styles.separator,
}}
onPress={(data , details = null) => {
setOriginPlace({data, details});
}}
renderRow={(data) =><PlaceRow data={data}/>}
fetchDetails={true}
enablePoweredByContainer={false}
currentLocation={true}
currentLocationLabel='Current Location'
query={{
key: GOOGLE_MAPS_APIKEY,
language: "en",
}}
renderRow={(data) => <PlaceRow data={data}/>}
renderDescription={(data) => data.description || data.vicinity}
predefinedPlaces={[homePlace, workPlace]}
/>
{/* Where To */}
<GooglePlacesAutocomplete
backgroundColor= "#eee"
nearbyPlacesAPI="GooglePlacesSearch"
placeholder="Where To?"
styles={{
textInput: styles.textInput,
container: {
...styles.autoCompleteContainer,
top: 50},
listView: {...styles.listView,
top: 50,
},
separator: styles.separator,
}}
onPress={(data , details = null) => {
setDestinationPlace({data, details});
}}
renderRow={(data) =><PlaceRow data={data}/>}
fetchDetails={true}
returnKeyType={"Search"}
enablePoweredByContainer={false}
query={{
key: GOOGLE_MAPS_APIKEY,
language: "en",
}}
/>
{/* Circle near origin Input */}
<View style = {styles.circle}/>
{/* Line between dots */}
<View style = {styles.line}/>
{/* Square near destination Input */}
<View style = {styles.square}/>
</View>
</SafeAreaView>
)
}
export default DestinationSearch;

The Mistake was in DestinationSearch
Mistake:
const checkNavigation = () => {
if (originPlace && destinationPlace) {
navigation.navigate('SearchResult'), {
originPlace,
destinationPlace,
}
}
}
Solution:
const checkNavigation = () => {
if (originPlace && destinationPlace) {
navigation.navigate("SearchResult",
{
originPlace,
destinationPlace,
})
}
}

Related

TypeError: undefined is not an object (evaluating 'navigation.replace')

MY login page
import React, { useState } from 'react'
import { TouchableOpacity, StyleSheet, View, ImageBackground } from 'react-native'
import { Text } from 'react-native-paper'
import Logo from '../Component/Logo'
import Header from '../Component/Header'
import Button from '../Component/Button'
import TextInput from '../Component/Inputtext'
import BackButton from '../Component/Backbutton'
import { theme } from '../core/theme'
import { emailValidator } from '../Component/emailval'
import { passwordValidator } from '../Component/Passwordval'
export default function LoginScreen({ navigation }) {
const [email, setEmail] = useState({ value: '', error: '' })
const [password, setPassword] = useState({ value: '', error: '' })
const onLoginPressed = () => {
const emailError = emailValidator(email.value)
const passwordError = passwordValidator(password.value)
if (emailError || passwordError) {
setEmail({ ...email, error: emailError })
setPassword({ ...password, error: passwordError })
return
}
navigation.reset({
index: 0,
routes: [{ name: 'Dashboard' }],
})
}
return (
<ImageBackground style={styles.image} source={require('../imgs/back.png') }>
<View>
<BackButton />
<Logo />
<Header style={styles.header}>Welcome back.</Header>
<TextInput
label="Email"
returnKeyType="next"
value={email.value}
onChangeText={(text) => setEmail({ value: text, error: '' })}
error={!!email.error}
errorText={email.error}
autoCapitalize="none"
autoCompleteType="email"
textContentType="emailAddress"
keyboardType="email-address"
style={styles.textmail}
/>
<TextInput
label="Password"
returnKeyType="done"
value={password.value}
onChangeText={(text) => setPassword({ value: text, error: '' })}
error={!!password.error}
errorText={password.error}
secureTextEntry
style={styles.textmail}
/>
<View style={styles.forgotPassword}>
<TouchableOpacity
onPress={() => navigation.navigate('ResetPasswordScreen')}
>
<Text style={styles.forgot}>Forgot your password?</Text>
</TouchableOpacity>
</View>
<Button mode="contained" onPress={onLoginPressed} style={styles.login}>
Login
</Button>
<View style={styles.row}>
<Text>Don’t have an account? </Text>
<TouchableOpacity onPress={() => navigation.replace('login')}>
<Text style={styles.link}>Sign up</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
)
}
const styles = StyleSheet.create({
forgotPassword: {
width: '100%',
alignItems: 'flex-end',
marginBottom: 24,
},
row: {
flexDirection: 'row',
marginTop: 4,
},
forgot: {
fontSize: 13,
color: '#414757',
},
link: {
fontWeight: 'bold',
color: '#560CCE',
},
header: {
fontSize: 21,
color: '#560CCE',
fontWeight: 'bold',
paddingVertical: 12,
},
image: {
width:'100%',
height: '100%',
},
textmail:{
backgroundColor:"#ffffff",
width:"90%",
alignSelf:'center',
borderRadius:40,
},
login:{
width:"70%"
}
})
App js::
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import OnboardingScreen from './Component/Onboardingscreen';
import LoginScreen from './Component/Loginscreen';
import Forgotpass from './Component/Forgotpassword';
import RegisterScreen from './Component/SignupScreen';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { useEffect } from 'react';
const AppStack = createStackNavigator();
const App =() => {
const [isFirstLaunch, setIsFirstLaunch,] = React.useState(null);
useEffect(() => {
AsyncStorage.getItem('alreadyLaunched').then(value => {
if(value == null) {
AsyncStorage.setItem('alreadyLaunched','true');
setIsFirstLaunch(true);
} else {
setIsFirstLaunch(false);
}
});
}, []);
if (isFirstLaunch == null) {
return null;
} else if ( isFirstLaunch == true ){
return (
<NavigationContainer>
<AppStack.Navigator
headerMode='none'
>
<AppStack.Screen name="OnboardingScreen" component={OnboardingScreen}/>
<AppStack.Screen name='login' component={LoginScreen} />
<AppStack.Screen name="RegisterScreen" component={RegisterScreen} />
<AppStack.Screen name="ResetPasswordScreen" component={Forgotpass} />
</AppStack.Navigator>
</NavigationContainer>
);
} else {
return <LoginScreen />;
}
}
export default App;
Error occur while i pressing "forgot password" and "signup" ,
all dependency is addad ,
it shows onpress error and i added error screenshot also there are following below,
ERROR TypeError: undefined is not an object (evaluating 'navigation.replace')
ERROR TypeError: undefined is not an object (evaluating 'navigation.replace')
Try using the useNavigation() hook:
import { useNavigation } from '#react-navigation/native';
export default function LoginScreen() {
const navigation = useNavigation();
return (
...
<TouchableOpacity onPress={() => navigation.replace('login')}>
<Text style={styles.link}>Sign up</Text>
</TouchableOpacity>
...
);
}
Single data in a array is deleted in api data so it's show
null is a not an object
Solution:give the absent value = null;

How to send a function to child component?

I want to know how I can send a function from my parent component to my child component. Because every time I get the error '"validationFunction" is not a function'. Very need your help. Also I will extend my SigIn component and add there another validation functions, so this is very important to me
SignIn component
import React, { Component } from 'react'
import { View } from 'react-native'
import { MyButton, MyTextInput, Header } from '../uikit'
import { styles } from '../constants/constants'
import { LOG_IN } from '../routes'
import { isEnoughSymbols } from '../validation/isEnoughSymbols'
export class SignIn extends Component {
state = {
symbolsValidation: true
}
isEnoughSymbols = (text) => {
if (text.trim().length < 8)
this.setState({ symbolsValidation: false })
}
render() {
const { mainContainer, buttons } = styles
return (
<View>
<View style={mainContainer}>
<MyTextInput
placeholder={'Email/Login'}
isSecure={false}
errorText={"Incorrect email format!"}
/>
<MyTextInput
placeholder={'Password'}
isSecure={true}
errorText={'Password must contain at least 8 symbols!'}
validationFunction={this.isEnoughSymbols.bind(this)}
/>
<MyTextInput
placeholder={'Confirm password'}
isSecure={true}
errorText={"Passwords don't match"}
/>
<View style={buttons}>
<MyButton
name={'confirm'.toUpperCase()}
onPress={() => this.props.navigation.navigate(LOG_IN)} />
</View>
</View>
</View>
)
}
}
And MyTextInput component
import React, {Component} from 'react'
import { TextInput, View, StyleSheet } from 'react-native'
import { w, width, h } from '../constants/constants'
import { ErrorMessage } from '.'
//import { isEnoughSymbols } from '../validation/isEnoughSymbols'
const MyTextInput = ({ placeholder, isSecure, errorText, validationFunction }) => {
let isValid = true
return (
<View style={styles.container}>
<TextInput
style={styles.text}
placeholder={placeholder}
secureTextEntry={isSecure}
onEndEditing={(e) => validationFunction(e.nativeEvent.text)}
>
</TextInput>
{
isValid ? null : <ErrorMessage
errorText={errorText}
/>
}
</View>
)
}
const styles = StyleSheet.create({
container: {
justifyContent: 'flex-start'
},
text: {
borderBottomWidth: 1,
borderColor: 'black',
fontSize: 30,
width: w - w / 10,
alignSelf: 'center',
textAlign: 'left',
marginTop: 20,
color: 'black'
},
}
)
export { MyTextInput }

Invariant Violation Text string must be rendered within a <Text> component

I'm really sorry to bother you, but I try to learn React-Native. I'm trying to make a weather app and I have this error :
Text strings must be rendered within a <Text> component.
- node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:4137:8 in <anonymous>
- node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:4134:2 in createTextInstance
- ... 9 more stack frames from framework internal
Here's are my two files of code:
weather-card.js
import React, {Component} from "react";
import {Animated, View, Text, PanResponder, Image} from "react-native";
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp
} from "react-native-responsive-screen";
const CARD_INITIAL_POSITION_Y = hp("80%");
const CARD_INITIAL_POSITION_X = wp("5%");
const TRESHOLD_TO_TOP = hp("75%");
const TRESHOLD_TO_BOTTOM = hp("70%");
const CARD_OPEN_POSITION = hp("45%");
const MAX_DRAG_ZONE_WHEN_OPEN = hp("65%");
const ICON_URL = "http://openweathermap.org/img/w/";
class WeatherCard extends Component {
state = { panResponder : undefined, isOpen: false};
componentDidMount() {
this.position = new Animated.ValueXY();
this.position.setValue({x:CARD_INITIAL_POSITION_X, y: CARD_INITIAL_POSITION_Y});
const panResponder = PanResponder.create({
onStartShouldSetPanResponder:() => true,
onPanResponderMove:(e,gesture) => {
if(!(this.state.isOpen && gesture.y0 > MAX_DRAG_ZONE_WHEN_OPEN)) {
this.position.setValue({
x:CARD_INITIAL_POSITION_X,
y: gesture.moveY
});
}
},
onPanResponderRelease:(e, gesture) => {
if (!this.state.isOpen){
if(gesture.moveY <= TRESHOLD_TO_TOP) {
this.setOpenPosition(() => this.setState({isOpen: true}));
} else {
this.resetPosition();
}
} else {
if(gesture.moveY <= TRESHOLD_TO_BOTTOM){
this.setOpenPosition()
} else {
if(gesture.y0 < MAX_DRAG_ZONE_WHEN_OPEN){
this.resetPosition(() => this.setState({isOpen: false}))
}
}
}
}
});
this.setState({panResponder})
}
setOpenPosition = (done) => {
Animated.spring(this.position, {
toValue: {x: CARD_INITIAL_POSITION_X, y : CARD_OPEN_POSITION}
}).start(() => done && done());
};
resetPosition = (done) => {
Animated.spring(this.position, {
toValue: {x: CARD_INITIAL_POSITION_X, y : CARD_INITIAL_POSITION_Y}
}).start(() => done && done())
};
getCardStyle() {
return {
width: wp("90%"),
height: hp("110%"),
borderRadius: 10,
zIndex: 2,
backgroundColor: "white",
elevation: 1,
shadowColor: "black",
shadowOpacity: 0.2,
shadowOffset: { height: 2, width: 2 },
position: "absolute",
left: CARD_INITIAL_POSITION_X,
padding: hp("2%"),
...this.position.getLayout()
};
}
renderHeader(){
return (
<View
style={{
justifyContent: "center",
alignItems: "center"
}}
>
<Text style={{ fontSize: 30, marginBottom: hp("1%") }}>
{this.props.currentWeather.name}
</Text>
<View style={{ flexDirection: "row" }}>
<Text style={{ marginTop: hp("1%"), fontSize: 35 }}>
{this.props.currentWeather.main.temp}
</Text>
<Image
style={{ height: 60, width: 60 }}
source={{
uri: `${ICON_URL}${this.props.currentWeather.weather[0].icon}.png`
}}
/>
</View>
</View>
)
}
render() {
return this.state.panResponder ? <Animated.View {...this.state.panResponder.panHandlers} style={this.getCardStyle()}> {this.renderHeader()} </Animated.View> : <View />;
}
}
export default WeatherCard;
And search-screen.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import MapView from 'react-native-maps';
import {SearchBar} from "react-native-elements";
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp
} from "react-native-responsive-screen";
import {connect} from "react-redux";
import {getCurrentWeatherByCity} from "../actions/index";
import WeatherCard from "../components/weather-card";
const DEFAULT_COORD = {
lat: 48.859268,
lng: 2.347060
};
class SearchScreen extends React.Component {
state={search: ""};
updateSearch = search => {
this.setState({search})
};
submitSearch = () => {
this.props.getCurrentWeatherByCity(this.state.search);
console.log(this.state.search)
};
render() {
console.log(this.props.currentWeather);
return (
<View style={styles.container}>
<MapView style={{flex : 1}}
region={{latitude : this.props.currentWeather ? this.props.currentWeather.coord.lat : DEFAULT_COORD.lat, longitude : this.props.currentWeather ? this.props.currentWeather.coord.lon : DEFAULT_COORD.lng, latitudeDelta: 0.2000, longitudeDelta: 0.1000}}
scrollEnabled={false}
liteMode={true} />
{this.props.currentWeather && <WeatherCard currentWeather={this.props.currentWeather} />}
<SearchBar
lightTheme
onChangeText={this.updateSearch}
value={this.state.search}
onSubmitEditing={this.submitSearch}
containerStyle={{
position: "absolute",
bottom: hp("50%"),
left: wp("5%"),
width: wp("90%")
}}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
const mapStateToProps = (store) => {
return {
currentWeather : store.weather.currentWeather
}
};
const mapDispatchToProps = {
getCurrentWeatherByCity
};
export default connect(mapStateToProps, mapDispatchToProps)(SearchScreen)
I was asking myself if the problem could be :
{this.props.currentWeather && <WeatherCard currentWeather={this.props.currentWeather} />}
Because it's not inside a Text component...
If you can help, it could be really great :D
If you need other resources, do not hesitate!
Thanks in advance :)
It might be because of this try this:
change
{this.props.currentWeather.name}
to
{this.props.currentWeather.name != undefined ? this.props.currentWeather.name : null}
Similarly do the above thing for {this.props.currentWeather.main.temp}
Hope this helps!
I would like to post my answer if someone has the same problem. The error says that a text string is "outside" a component. However it wasn't the case. It was indentation's problem. So don't forget to pay attention about that :D Expo can be mean !

react-navigation drawer updating multiple times

I am building an application with React Native and React Navigation, I have made all the settings and it is working, however, when the drawer is fired the image is updated multiple times causing spikes and failures to trigger buttons contained in it.
e.g.:
I am using:
react: 16.8.3,
react-native: 0.59.1,
react-native-ui-kitten: ^3.1.2,
react-navigation: ^3.4.0
I was using version 3 of RN and to try to solve I went back to version 2 but without success.
I put some warnings in the method that executes the image and saw that it is called whenever there is this update.
I already changed the image in different sizes and formats but it also did not help.
I already tested on cell phones and emulators but with no success.
Drawer:
import React, { Component } from 'react';
import {
TouchableHighlight,
View,
ScrollView,
Image,
Platform,
StyleSheet,
} from 'react-native';
import {
RkStyleSheet,
RkText,
RkTheme,
} from 'react-native-ui-kitten';
import Icon from 'react-native-vector-icons/Ionicons';
import Routes from '../../config/navigation/routes';
import logo from '../../assets/smallLogo.png';
export default function SideNavigation(props) {
const onMenuItemPressed = item => {
props.navigation.navigate(item.id);
};
const renderIcon = () => (<Image style={styles.image} source={logo}/>);
const renderMenuItem = item => (
<TouchableHighlight style={styles.container} key={item.id} underlayColor={RkTheme.current.colors.button.underlay} activeOpacity={1} onPress={() => onMenuItemPressed(item)}>
<View style={styles.content}>
<View style={styles.content}>
<RkText style={styles.icon} rkType='moon primary xlarge'><Icon name={item.icon} size={25}/></RkText>
<RkText rkType='regular'>{item.title}</RkText>
</View>
{/*<RkText rkType='awesome secondaryColor small'>{FontAwesome.chevronRight}</RkText>*/}
</View>
</TouchableHighlight>
);
const renderMenu = () => Routes.map(renderMenuItem);
return (
<View style={styles.root}>
<ScrollView showsVerticalScrollIndicator={false}>
<View style={[styles.container, styles.content]}>
{renderIcon()}
</View>
{renderMenu()}
</ScrollView>
</View>
)
}
const styles = RkStyleSheet.create(theme => ({
container: {
height: 60,
paddingHorizontal: 16,
borderTopWidth: StyleSheet.hairlineWidth,
borderColor: theme.colors.border.base,
},
root: {
paddingTop: Platform.OS === 'ios' ? 20 : 0,
backgroundColor: theme.colors.screen.base
},
content: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
},
icon: {
marginRight: 13,
},
image:{
resizeMode: 'contain',
maxWidth: 125
}
}));
Drawer setup:
import React, {Component} from 'react';
import { View, Text} from 'react-native';
import Login from './screens/login';
import PasswordRecovery from './screens/passwordRecovery';
import Home from './screens/home';
import SideNavigator from './components/sideMenu';
import { bootstrap } from './config/bootstrap';
import {
createDrawerNavigator,
createStackNavigator,
createAppContainer
} from 'react-navigation';
import { withRkTheme } from 'react-native-ui-kitten';
import NavBar from './components/navBar';
import AppRoutes from './config/navigation/routesBuilder';
import Splash from './screens/splash';
bootstrap();
const renderHeader = (navigation, props) => {
const ThemedNavigationBar = withRkTheme(NavBar);
return (
<ThemedNavigationBar navigation={navigation} headerProps={props} />
);
};
const App = createStackNavigator({
Splash: Splash,
Login: Login,
PasswordRecovery: PasswordRecovery,
Main: createDrawerNavigator({
...AppRoutes
},{
contentComponent: props => {
const SideNav = withRkTheme(SideNavigator);
return <SideNav {...props}/>
}
}),
},
{
headerMode: 'none',
})
export default createAppContainer(App);
Routes setup:
import React from 'react';
import _ from 'lodash';
import { createStackNavigator } from 'react-navigation';
import { withRkTheme } from 'react-native-ui-kitten';
import transition from './transitions';
import Routes from './routes';
import NavBar from '../../components/navBar';
const main = {};
const flatRoutes = {};
const routeMapping = (route) => ({
screen: withRkTheme(route.screen),
title: route.title,
});
(Routes).forEach(route => {
flatRoutes[route.id] = routeMapping(route);
main[route.id] = routeMapping(route);
route.children.forEach(nestedRoute => {
flatRoutes[nestedRoute.id] = routeMapping(nestedRoute);
});
});
const renderHeader = (navigation, props) => {
const ThemedNavigationBar = withRkTheme(NavBar);
return (
<ThemedNavigationBar navigation={navigation} headerProps={props} />
);
};
const DrawerRoutes = Object.keys(main).reduce((routes, name) => {
const rawRoutes = routes;
rawRoutes[name] = {
name,
screen: createStackNavigator(flatRoutes, {
initialRouteName: name,
headerMode: 'screen',
cardStyle: { backgroundColor: 'transparent' },
transitionConfig: transition,
defaultNavigationOptions: ({ navigation }) => ({
gesturesEnabled: false,
header: (props) => renderHeader(navigation, props),
}),
}),
};
return rawRoutes;
}, {});
const AppRoutes = DrawerRoutes;

Why doesn't the nested stack navigation work in react native?

I'm a beginner programmer and I'm trying to created a nested navigator in react native. The stack navigator on the Home screen works but the stack navigator on the MyEvents Screen does not. I use the tabs to navigate between Home and MyEvents and within the those pages I want to use a stack navigator to get to other pages. Please help! (also please let me know if I am being unclear)
This is Router.js
import React from 'react';
import {StackNavigator, TabNavigator} from 'react-navigation';
import InputScreen from './InputPage';
import HomeScreen from './Home';
import DetailsScreen from './Details';
import MyEventsScreen from './MyEvents';
import EditScreen from './EditPage';
import MapScreen from './Map';
const BottomNavigation = require('react-native-bottom-navigation');
export const Tabs = TabNavigator({
Home: {screen: HomeScreen},
EventMap: {screen: MapScreen},
Input: {screen: InputScreen},
MyEvents:{screen: MyEventsScreen},
},{
tabBarOptions: {
activeTintColors: '#e91e63',
//swipeEnabled: true,
}
});
export const EventsStack = StackNavigator({
Home: {
screen: Tabs,
},
Details: {
screen: DetailsScreen,
navigationOptions: {
header: null,
},
},
});
export const MyEventsStack = StackNavigator({
MyEvents: {
screen: Tabs,
navigationOptions: {
header: null
}
},
MyEventsDetails: {
screen: EditScreen,
navigationOptions: {
header: null,
/*navigation: ({ navigation }) => ({
title: `${navigation.state.params.name.first.toUpperCase()} ${navigation.state.params.name.last.toUpperCase()}`,
}),*/
},
},
});
export const Root = StackNavigator({
TabNav: {
screen: EventsStack,
}
}, {headerMode: 'none'});
This is Home.js
import React, {Component} from 'react';
import {View, Text, TouchableHighlight, SectionList} from 'react-native';
import {ListItem} from 'react-native-elements';
import {firebaseApp} from './App';
import Icon from 'react-native-vector-icons/MaterialIcons';
import {StackNavigator, TabNavigator} from 'react-navigation';
import {Tabs} from './Router';
export default class HomeScreen extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
this.itemsRef = firebaseApp.database().ref().child('items');
console.ignoredYellowBox = [
'Setting a timer'
];
}
onLearnMore = (item) => {
this.props.navigation.navigate('Details', {
...item
});
};
static navigationOptions = {
tabBarLabel: 'Home',
tabBarIcon: ({tintColor}) => (
<Icon
name = {'Home'}
size = {26}
style = {{color: tintColor}} />
)
}
listenForItems(itemsRef) {
itemsRef.on('value', (snap) => {
// get children as an array
var items = [];
snap.forEach((parent) => {
var children = [];
parent.forEach((child) => {
children.push({
"name": child.val().name,
"when": child.val().when,
"who": child.val().who,
});
});
items.push({
data: children,
key: parent.key.toUpperCase(),
})
});
this.setState({
data: items
});
});
}
componentDidMount() {
this.listenForItems(this.itemsRef);
}
render() {
var styles = require('./Styles');
const {navigate} = this.props.navigation;
return (
<View style={{flex: 1}}>
<View style={styles.header}>
<Text style={styles.title}>Princeton Events</Text>
</View>
<View style={styles.body}>
<SectionList renderItem={({item}) => <ListItem style={styles.item}
title={item.name} subtitle={item.when}
onPress={() => this.onLearnMore(item)}/>}
renderSectionHeader={({section}) =>
<Text style={styles.sectionHeader}>{section.key}</Text>}
sections={this.state.data} keyExtractor={(item) => item.name}/>
</View>
</View>
);
}
}
This is MyEvents.js
import React, {Component} from 'react';
import {View, Text, TouchableHighlight, FlatList} from 'react-native';
import {ListItem, List} from 'react-native-elements';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Router from './Router';
export default class MyEventsScreen extends Component {
onViewMyEvent = (item) => {
this.props.navigation.navigate('Edit', {
...item
});
};
static navigationOptions = {
tabBarLabel: 'MyEvents',
tabBarIcon: ({tintColor}) => (
<Icon
name = {'account circle'}
size = {26}
style = {{color: tintColor}} />
)
}
render() {
var styles = require('./Styles');
const {navigate} = this.props.navigation;
return (
<View style={{
flex: 1
}}>
<View style={styles.header}>
<Text style={styles.title}>My Events</Text>
</View>
<View style={styles.body}>
<List containerStyle={{
borderTopWidth: 0,
borderBottomWidth: 0
}}>
<FlatList data={[
{
"name": "Event 1",
"who": "E-Club",
"what": "description goes here description goes here description goes here",
"when": "1:00",
"where": "Ehub",
"RSVP": "yes"
}, {
"name": "Event 2",
"who": "Club 2",
"what": "description goes here",
"when": "2:00",
"where": "Location 2",
"RSVP": "no"
}
]} renderItem={({item}) => <ListItem style={styles.item} title={item.name} subtitle={item.when} containerStyle={{
borderBottomWidth: 0
}} onPress={() => this.onViewMyEvent(item)}/>} keyExtractor={(item, index) => index}/>
</List>
</View>
<View style={styles.footer}>
<TouchableHighlight style={styles.button} onPress={() => navigate('Home')} underlayColor='#ffd199'>
<Text style={styles.buttonText}>Back</Text>
</TouchableHighlight>
</View>
</View>
);
}
}

Categories