React navigation withNavigation HOC not working in carousel - javascript

I'm making a react-native app using expo I'm using the snap-in-carousel library
I want when someone click on the carousel it navigate here is the code
import React, { Component } from 'react';
import { withNavigation } from 'react-navigation';
export default class SliderEntry extends Component {
static propTypes = {
data: PropTypes.object.isRequired,
even: PropTypes.bool,
parallax: PropTypes.bool,
parallaxProps: PropTypes.object
};
get image () {
const { data: { illustration }, parallax, parallaxProps, even } = this.props;
return parallax ? (
<ParallaxImage
source={{ uri: illustration }}
containerStyle={[styles.imageContainer, even ? styles.imageContainerEven : {}]}
style={styles.image}
parallaxFactor={0.35}
showSpinner={true}
spinnerColor={even ? 'rgba(255, 255, 255, 0.4)' : 'rgba(0, 0, 0, 0.25)'}
{...parallaxProps}
/>
) : (
<Image
source={{ uri: illustration }}
style={styles.image}
/>
);
}
render () {
const { data: { title, subtitle}, even, navigation } = this.props;
const uppercaseTitle = title ? (
<Text
style={[styles.title, even ? styles.titleEven : {}]}
numberOfLines={2}
>
{ title.toUpperCase() }
</Text>
) : false;
return (
<TouchableOpacity
activeOpacity={1}
style={styles.slideInnerContainer}
onPress={() => navigation.push('ProfileScreen', {category: title })}
>
<View style={styles.shadow} />
<View style={[styles.imageContainer, even ? styles.imageContainerEven : {}]}>
{ this.image }
<View style={[styles.radiusMask, even ? styles.radiusMaskEven : {}]} />
</View>
<View style={[styles.textContainer, even ? styles.textContainerEven : {}]}>
{ uppercaseTitle }
<Text
style={[styles.subtitle, even ? styles.subtitleEven : {}]}
numberOfLines={2}
>
{ subtitle }
</Text>
</View>
</TouchableOpacity>
);
}
}
i get undefined is not an object (evaluating 'navigation.push')
here is a link to the project on Github: https://github.com/Ov3rControl/Weddi

You're not actually using withNavigation, you're just importing it. You need to pass your component class into the withNavigation HOC.
The way withNavigation works is, you pass in your component, and withNavigation adds the navigation object as a prop to your component.
You're not doing that, hence why this.props.navigation is undefined.
See your modified code below, the export default expression has moved to the bottom, being passed withNavigation(SliderEntry).
Read the manual. https://reactnavigation.org/docs/en/with-navigation.html
import React, { Component } from 'react';
import { withNavigation } from 'react-navigation';
class SliderEntry extends Component {
static propTypes = {
data: PropTypes.object.isRequired,
even: PropTypes.bool,
parallax: PropTypes.bool,
parallaxProps: PropTypes.object
};
get image () {
const { data: { illustration }, parallax, parallaxProps, even } = this.props;
return parallax ? (
<ParallaxImage
source={{ uri: illustration }}
containerStyle={[styles.imageContainer, even ? styles.imageContainerEven : {}]}
style={styles.image}
parallaxFactor={0.35}
showSpinner={true}
spinnerColor={even ? 'rgba(255, 255, 255, 0.4)' : 'rgba(0, 0, 0, 0.25)'}
{...parallaxProps}
/>
) : (
<Image
source={{ uri: illustration }}
style={styles.image}
/>
);
}
render () {
const { data: { title, subtitle}, even, navigation } = this.props;
const uppercaseTitle = title ? (
<Text
style={[styles.title, even ? styles.titleEven : {}]}
numberOfLines={2}
>
{ title.toUpperCase() }
</Text>
) : false;
return (
<TouchableOpacity
activeOpacity={1}
style={styles.slideInnerContainer}
onPress={() => navigation.push('ProfileScreen', {category: title })}
>
<View style={styles.shadow} />
<View style={[styles.imageContainer, even ? styles.imageContainerEven : {}]}>
{ this.image }
<View style={[styles.radiusMask, even ? styles.radiusMaskEven : {}]} />
</View>
<View style={[styles.textContainer, even ? styles.textContainerEven : {}]}>
{ uppercaseTitle }
<Text
style={[styles.subtitle, even ? styles.subtitleEven : {}]}
numberOfLines={2}
>
{ subtitle }
</Text>
</View>
</TouchableOpacity>
);
}
}
// See the component is being wrapped with withNavigation.
export default withNavigation(SliderEntry);

Related

I was to implement CustomPicker in my functional component in react native

Please tell me that
if I want to change the CustomExample Class component into a functional component
**as: ** const CustomExample = () =>{...}
then how will change the following code to work in similar manner:
<CustomPicker
placeholder={'Please select your favorite item...'}
options={options}
getLabel={item => item.label}
fieldTemplate={this.renderField}
optionTemplate={this.renderOption}
/>
I have tried following methods:
changing definition as
rederField(settings){...} to const renderField = (settings) => {...}
and then assigning renderField to fieldTemplate as follow:
* fieldTemplate={renderField()}
* fieldTemplate={()=>renderField()}
* fieldTemplate={renderField(selectedItem,defaultText,getLabel,clear)}
on each attempt it showed some error.
PLZ HELP ME I'M STUCK ON IT FROM LAST FEW DAYS
GOING THROUGH ALL THE DOCS WILL TAKE MONTHS FOR ME.
import * as React from 'react'
import { Alert, Text, View, TouchableOpacity, StyleSheet } from 'react-native'
import { CustomPicker } from 'react-native-custom-picker'
export class CustomExample extends React.Component {
render() {
const options = [
{
color: '#2660A4',
label: 'One',
value: 1
},
{
color: '#FF6B35',
label: 'Two',
value: 2
},
]
return (
<View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
<CustomPicker
placeholder={'Please select your favorite item...'}
options={options}
getLabel={item => item.label}
fieldTemplate={this.renderField}
optionTemplate={this.renderOption}
/>
</View>
)
}
renderField(settings) {
const { selectedItem, defaultText, getLabel, clear } = settings
return (
<View style={styles.container}>
<View>
{!selectedItem && <Text style={[styles.text, { color: 'grey' }]}>{defaultText}</Text>}
{selectedItem && (
<View style={styles.innerContainer}>
<TouchableOpacity style={styles.clearButton} onPress={clear}>
<Text style={{ color: '#fff' }}>Clear</Text>
</TouchableOpacity>
<Text style={[styles.text, { color: selectedItem.color }]}>
{getLabel(selectedItem)}
</Text>
</View>
)}
</View>
</View>
)
}
renderOption(settings) {
const { item, getLabel } = settings
return (
<View style={styles.optionContainer}>
<View style={styles.innerContainer}>
<View style={[styles.box, { backgroundColor: item.color }]} />
<Text style={{ color: item.color, alignSelf: 'flex-start' }}>{getLabel(item)}</Text>
</View>
</View>
)
}
}
// STYLE FILES PRESENT HERE.
change the definition of function to
function renderOption(settings) {...}
function renderField (settings) {...}
and call function like this.
<CustomPicker
placeholder={'Please select your favorite item...'}
options={options}
getLabel={item => item.label}
fieldTemplate={renderField}
optionTemplate={renderOption}
/>

React native, undefined is not an object And handle onChange

I made 2 screens home and editing screen. I want to change values from edit screen without redux and context but I don't know how? and also when I click save in editscreen it's throwing error that undefined is not an object (evaluating '_this.props.navigation.goBack') and displaing blank home screencwhy that's happening. Can some one help me please, below is my code
home.js
class Home extends Component {
state = {
modal: false,
editMode: false.
post: [
{
key: "1",
title: "A Good Boi",
des: "He's a good boi and every one know it.",
image: require("../assets/dog.jpg"),
},
{
key: "2",
title: "John Cena",
des: "As you can see, You can't see me!",
image: require("../assets/cena.jpg"),
},
],
};
addPost = (posts) => {
posts.key = Math.random().toString();
this.setState((prevState) => {
return {
post: [...prevState.post, posts],
modal: false,
};
});
};
onEdit = (data) => {
this.setState({ post: { title: data }, editMode: false });
};
render() {
if (this.state.editMode)
return <EditScreen item={item} onEdit={this.onEdit} />;
return (
<Screen style={styles.screen}>
<Modal visible={this.state.modal} animationType="slide">
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.modalContainer}>
<AddPost addPost={this.addPost} />
</View>
</TouchableWithoutFeedback>
</Modal>
<FlatList
data={this.state.post}
renderItem={({ item }) => (
<>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => this.setState({ editMode: true })}
style={styles.Edit}
>
<MaterialCommunityIcons
name="playlist-edit"
color="green"
size={35}
/>
</TouchableOpacity>
<Card>
<Image style={styles.image} source={item.image} />
<View style={styles.detailContainer}>
<Text style={styles.title} numberOfLines={1}>
{item.title}
</Text>
<Text style={styles.subTitle} numberOfLines={2}>
{item.des}
</Text>
</View>
</Card>
</>
)}
/>
</Screen>
Edit.js
import React, { Component } from "react";
import { View, StyleSheet, Image, KeyboardAvoidingView } from "react-native";
import colors from "../config/colors";
import AppButton from "../components/AppButton";
import AppTextInput from "../components/AppTextInput";
class EditScreen extends Component {
render() {
const { item, onEdit, onClose } = this.props;
return (
<KeyboardAvoidingView
behavior="position"
keyboardVerticalOffset={Platform.OS === "ios" ? 0 : 100}
>
<Image style={styles.image} source={item.image} />
<View style={styles.detailContainer}>
<AppTextInput value={item.title} />
<AppTextInput value={item.des} />
</View>
<AppButton
text="Save"
onPress={() => {
onEdit(this.state);
}}
/>
</KeyboardAvoidingView>
);
}
}
export default EditScreen;
AppTextInput.js
function AppTextInput({ icon, width = "100%", ...otherProps }) {
return (
<View style={[styles.container, { width }]}>
<TextInput
placeholderTextColor={defaultStyles.colors.medium}
style={defaultStyles.text}
{...otherProps}
/>
</View>
);
}
Try this:
Edit.js
import React, { Component } from 'react';
import { View, StyleSheet, Image, KeyboardAvoidingView } from 'react-native';
import colors from '../config/colors';
import AppButton from '../components/AppButton';
import AppTextInput from '../components/AppTextInput';
class EditScreen extends Component {
constructor(props) {
super(props);
this.state = { ...props.item };
}
render() {
const { onEdit, onClose } = this.props;
const { title, des, image } = this.state;
return (
<KeyboardAvoidingView
behavior="position"
keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 100}>
<Image style={styles.image} source={image} />
<View style={styles.detailContainer}>
<AppTextInput
value={title}
onChangeText={text => this.setState({ title: text })}
/>
<AppTextInput
value={des}
onChangeText={text => this.setState({ des: text })}
/>
</View>
<AppButton text="Save" onPress={() => onEdit(this.state)} />
</KeyboardAvoidingView>
);
}
}
export default EditScreen;
onEdit
onEdit = data => {
const newPosts = this.state.post.map(item => {
if(item.key === data.key) return data;
else return item;
})
this.setState({ post: newPosts, editMode: false });
};
Only the direct children of a navigator can access
this.props.navigation
If you want to access that inside the edit screen you can pass it from the Home screen as a prop. Like so:
return <EditScreen item={item} onEdit={this.onEdit} navigation={this.props.navigation} />;
But i don't think you need to go back because you are still on the Home page and just rendering the EditScreen within it. So just changing the state to have editMode: false should be enough

configuration with the .map() in arrays. Fetching data from firebase and outputting in a tinder-like card view in React Native

Here, I am fetching data from firebase and then trying to output it in a tinder card like format. My code is as follows -
import React from 'react';
import { View, ImageBackground, Text, Image, TouchableOpacity } from 'react-native';
import CardStack, { Card } from 'react-native-card-stack-swiper';
import City from '../components/City';
import Filters from '../components/Filters';
import CardItem from '../components/CardItem';
import styles from '../assets/styles';
import Demo from '../assets/demo';;
import {db} from '../config/config';
class Home extends React.Component {
constructor (props) {
super(props);
this.state = ({
items: [],
isReady: false,
});
}
componentWillMount() {
let items = [];
db.ref('cards').once('value', (snap) => {
snap.forEach((child) => {
let item = child.val();
item.id = child.key;
items.push({
name: child.val().pet_name,
description: child.val().pet_gender,
pet_age: child.val().pet_age,
pet_breed: child.val().pet_breed,
photoUrl: child.val().photoUrl,
});
});
//console.log(items)
this.setState({ items: items, isReady: true });
console.log(items);
});
}
componentWillUnmount() {
// fix Warning: Can't perform a React state update on an unmounted component
this.setState = (state,callback)=>{
return;
};
}
render() {
return (
<ImageBackground
source={require('../assets/images/bg.png')}
style={styles.bg}
>
<View style={styles.containerHome}>
<View style={styles.top}>
<City />
<Filters />
</View>
<CardStack
loop={true}
verticalSwipe={false}
renderNoMoreCards={() => null}
ref={swiper => {
this.swiper = swiper
}}
>
{this.state.items.map((item, index) => (
<Card key={index}>
<CardItem
//image={item.image}
name={item.name}
description={item.description}
actions
onPressLeft={() => this.swiper.swipeLeft()}
onPressRight={() => this.swiper.swipeRight()}
/>
</Card>
))}
</CardStack>
</View>
</ImageBackground>
);
}
}
export default Home;
I am fetching data and storing it in an array called items[]. Console.log(items) gives me the following result:
Array [
Object {
"description": "male",
"name": "dawn",
"pet_age": "11",
"pet_breed": "golden retriever",
"photoUrl": "picture",
},
Object {
"description": "Male",
"name": "Rambo",
"pet_age": "7",
"pet_breed": "German",
"photoUrl": "https://firebasestorage.googleapis.com/v0/b/woofmatix-50f11.appspot.com/o/pFkdnwKltNVAhC6IQMeSapN0dOp2?alt=media&token=36087dae-f50d-4f1d-9bf6-572fdaac8481",
},
]
Furthermore, I want to output my data in a card like outlook so I made a custom component called CardItem:
import React from 'react';
import styles from '../assets/styles';
import { Text, View, Image, Dimensions, TouchableOpacity } from 'react-native';
import Icon from './Icon';
const CardItem = ({
actions,
description,
image,
matches,
name,
pet_name,
pet_gender,
pet_age,
onPressLeft,
onPressRight,
status,
variant
}) => {
// Custom styling
const fullWidth = Dimensions.get('window').width;
const imageStyle = [
{
borderRadius: 8,
width: variant ? fullWidth / 2 - 30 : fullWidth - 80,
height: variant ? 170 : 350,
margin: variant ? 0 : 20
}
];
const nameStyle = [
{
paddingTop: variant ? 10 : 15,
paddingBottom: variant ? 5 : 7,
color: '#363636',
fontSize: variant ? 15 : 30
}
];
return (
<View style={styles.containerCardItem}>
{/* IMAGE */}
<Image source={image} style={imageStyle} />
{/* MATCHES */}
{matches && (
<View style={styles.matchesCardItem}>
<Text style={styles.matchesTextCardItem}>
<Icon name="heart" /> {matches}% Match!
</Text>
</View>
)}
{/* NAME */}
<Text style={nameStyle}>{name}</Text>
{/* DESCRIPTION */}
{description && (
<Text style={styles.descriptionCardItem}>{description}</Text>
)}
{/* STATUS */}
{status && (
<View style={styles.status}>
<View style={status === 'Online' ? styles.online : styles.offline} />
<Text style={styles.statusText}>{pet_age}</Text>
</View>
)}
{/* ACTIONS */}
{actions && (
<View style={styles.actionsCardItem}>
<View style={styles.buttonContainer}>
<TouchableOpacity style={[styles.button, styles.red]} onPress={() => {
this.swiper.swipeLeft();
}}>
<Image source={require('../assets/red.png')} resizeMode={'contain'} style={{ height: 62, width: 62 }} />
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.orange]} onPress={() => {
this.swiper.goBackFromLeft();
}}>
<Image source={require('../assets/back.png')} resizeMode={'contain'} style={{ height: 32, width: 32, borderRadius: 5 }} />
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.green]} onPress={() => {
this.swiper.swipeRight();
}}>
<Image source={require('../assets/green.png')} resizeMode={'contain'} style={{ height: 62, width: 62 }} />
</TouchableOpacity>
</View>
</View>
)}
</View>
);
};
export default CardItem;
The problem is when I try to pass the data in my items[] array, the cardItem component just doesnt work. To dry-run, I used a sample demo array and when I use the Demo array, my component works just fine. What am I doing wrong? I have been tinkering with this problem for quite a while now. Any help whatsoever would be appreciated.

typeError: undefined is not an object (evaluating 'item.phoneNumbers[0]')

I want to render my contact list in my app using expo-contacts, the list display for about 2 seconds, then i get typeError: undefined is not an object (evaluating 'item.phoneNumbers[0]'). I have checked the documentation to see if I made any errors, but i could not find any. Does anyone have a work around this
below is my code
ContactList.js
import React, { Component } from "react";
import {
View,
Text,
Platform,
StatusBar,
FlatList,
StyleSheet,
ActivityIndicator
} from "react-native";
import * as Contacts from "expo-contacts";
import * as Permissions from "expo-permissions";
class ContactList extends Component {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = {
isLoading: false,
contacts: []
};
}
async componentDidMount() {
this.setState({
isLoading: true
});
this.loadContacts();
}
loadContacts = async () => {
const permissions = await Permissions.askAsync(Permissions.CONTACTS);
if (permissions.status !== "granted") {
return;
}
const { data } = await Contacts.getContactsAsync({
fields: [Contacts.Fields.PhoneNumbers, Contacts.Fields.Emails]
});
this.setState({
contacts: data,
isLoading: false
});
};
handleBack() {
this.props.navigation.goBack();
}
renderItem = ({ item }) => (
<View style={{ minHeight: 70, padding: 5 }}>
<Text>
{item.firstName}
{item.lastName}
</Text>
<Text>{item.phoneNumbers[0].digits}</Text>
</View>
);
render() {
const { isLoading, contacts } = this.state;
let emptyContact = null;
emptyContact = (
<View style={styles.emptyContactStyle}>
<Text style={{ color: "red" }}>No Contacts Found</Text>
</View>
);
return (
<SafeAreaView style={styles.contentWrapper}>
<View style={styles.contentWrapper}>
{isLoading ? (
<View style={styles.isLoadingStyle}>
<ActivityIndicator size="large" color="#2484E8" />
</View>
) : null}
<FlatList
data={contacts}
renderItem={this.renderItem}
keyExtractor={(item, index) => index.toString()}
ListEmptyComponent={emptyContact}
/>
</View>
</SafeAreaView>
);
}
}
Here is a new answer because the previous one was off topic. The error occurs because the displayed contact doesn't have a phoneNumber.
You should check first that a phone number exists before displaying it:
renderItem = ({ item }) => (
<View style={{ minHeight: 70, padding: 5 }}>
<Text>
{item.firstName}
{item.lastName}
</Text>
<Text>
{item.phoneNumbers && item.phoneNumbers[0] && item.phoneNumbers[0].digits}
</Text>
</View>
);

Can't make conditional rendering

I have Header component which I would like to use in multiple screens with multiple use cases such as in MainScreen I want to show only profile icon whereas in other screens I would like to use both backButton and profile icon.
I get isProfileIconVisible and isBackButtonIconVisible from props in Header Component.
this.state = {
isProfileIconVisible: props.isProfileIconVisible,
isBackButtonIconVisible: props.isBackButtonIconVisible
}
I have rendering functions.
_renderProfileIcon () {
let profileIcon = (
<View style={styles.profileButtonContainer} >
<CustomIconButton
onPress={this.props.onProfilePress}
></CustomIconButton>
</View>
);
return profileIcon;
};
_renderBackButtonIcon () {
let backButonIcon = (
<View style={styles.backButtonContainer} >
<CustomIconButton
onPress={this.props.onBackPress}
iconName={"arrow-left"}
></CustomIconButton>
</View>
);
return backButonIcon;
};
and in main render function I am making conditional rendering:
render() {
const { style, isBackButtonIconVisible, isProfileIconVisible, ...otherProps } = this.props;
return (
<View style={styles.container}>
{isBackButtonIconVisible ? this._renderBackButtonIcon : null}
<View style={styles.textContainer} >
<Text style={styles.text}>{this.props.text}</Text>
</View>
{isProfileIconVisible ? this._renderProfileIcon : null}
</View>
)
}
with this setup, I am not able to render either ProfileIcon nor BackButtonIcon.
I got the text prop but not icons.
Header Component propTypes and defaultProps:
Header.propTypes = {
onBackPress: PropTypes.func,
onProfilePress: PropTypes.func,
text: PropTypes.string,
backButtonIconName: PropTypes.string,
isProfileIconVisible: PropTypes.bool,
isBackButtonIconVisible: PropTypes.bool,
};
Header.defaultProps = {
backButtonIconName: 'keyboard-backspace',
isProfileIconVisible: true,
isBackButtonIconVisible: true,
}
And this is how I call Header component from another component:
<Header
text={"Welcome!"}
isProfileIconVisible={true}
isBackButtonIconVisible={false}
onProfilePress={this.handleProfileButtonPress}
style={styles.headerContainer}
/>
Can you help me where I am doing wrong?
Thank you.
Your _renderBackButtonIcon and _renderProfileIcon are functions, you need to call them to get their return values:
render() {
const { style, isBackButtonIconVisible, isProfileIconVisible, ...otherProps } = this.props;
return (
<View style={styles.container}>
{isBackButtonIconVisible ? this._renderBackButtonIcon() : null}
<View style={styles.textContainer} >
<Text style={styles.text}>{this.props.text}</Text>
</View>
{isProfileIconVisible ? this._renderProfileIcon() : null}
</View>
)
}
Note the () after this._renderBackButtonIcon and this._renderProfileIcon.
Side note: There's no reason to have ...otherProps here:
const { style, isBackButtonIconVisible, isProfileIconVisible, ...otherProps } = this.props;
You never use it.
There is an argument for adding text to that list and using it, rather than this.props.text within the return value:
render() {
const { style, isBackButtonIconVisible, isProfileIconVisible, text } = this.props;
return (
<View style={styles.container}>
{isBackButtonIconVisible ? this._renderBackButtonIcon() : null}
<View style={styles.textContainer} >
<Text style={styles.text}>{text}</Text>
</View>
{isProfileIconVisible ? this._renderProfileIcon() : null}
</View>
)
}

Categories