I built a cutom model picker in react native. But when I select an item in the list it is not showing the selected value.
custom picker code
function ItemPicker({
icon,
items,
onSelectItem,
placeholder,
selectedItem,
label,
}) {
const [modalVisible, setModalVisible] = useState(false);
return (
<>
<TouchableWithoutFeedback onPress={() => setModalVisible(true)}>
<View style={styles.container}>
{icon && (
<MaterialCommunityIcons
name={icon}
size={20}
color={colors.medium}
style={styles.icon}
/>
)}
<Text style={styles.text}>
{selectedItem ? selectedItem.label : placeholder}
</Text>
<MaterialCommunityIcons
name="chevron-down"
size={20}
color={colors.gray}
/>
</View>
</TouchableWithoutFeedback>
<Modal visible={modalVisible} animationType="fade">
<View>
<Button title="Close" onPress={() => setModalVisible(false)} />
<FlatList
data={items}
keyExtractor={(item) => item.value.toString()}
persistentScrollbar
renderItem={({ item }) => (
<TouchableOpacity
label={item.label}
onPress={() => {
setModalVisible(false);
// onSelectItem(item);
}}
>
<Text style={styles.pickertext}>{item.label}</Text>
</TouchableOpacity>
)}
/>
</View>
</Modal>
</>
);
}
Item list and picker
const months = [
{ label: "January", value: 1 },
{ label: "Feburary", value: 2 },
{ label: "March", value: 3 },
{ label: "April", value: 4 },
{ label: "May", value: 5 },
{ label: "June", value: 6 },
{ label: "July", value: 7 },
{ label: "August", value: 8 },
{ label: "September", value: 9 },
{ label: "October", value: 10 },
{ label: "November", value: 11 },
{ label: "December", value: 12 },
];
<ItemPicker
selectedItem={month}
value={month}
months={months}
onSelectItem={(item) => setMonth(item.value)}
items={months}
icon="calendar-month"
placeholder="Choose Month"
/>
Here when I change the item picker's property onSelectItem={(item) => setMonth(item.value)} to onSelectItem={(item) => setMonth(item)} it's showing the selected item but the value doesn't submit.
output when onSelectItem={(item) => setMonth(item.value)}
output when onSelectItem={(item) => setMonth(item)}
How can I fix this?
Your problem is that ItemPicker is expecting selectedItem to be an object rather than a number. If you want month to be a number, then you have to change selectedItem to
<ItemPicker
selectedItem={months[month-1]}
value={month}
months={months}
onSelectItem={(item) => setMonth(item.value)}
items={months}
icon="calendar-month"
placeholder="Choose Month"
/>
If you are fine with month being an object rather than a number:
<ItemPicker
selectedItem={month}
value={month}
months={months}
onSelectItem={setMonth}
items={months}
icon="calendar-month"
placeholder="Choose Month"
/>
It may also be better in ItemPicker to change
<Text style={styles.text}>
{selectedItem ? selectedItem.label : placeholder}
</Text>
to
<Text style={styles.text}>
{selectedItem?.label || placeholder}
</Text>
Related
Context:
In a single screen view, there are 2 dropdowns (made using react-native-autocomplete-dropdown) but only 1 is visible at a time. The other dropdown comes into view when the user toggles the next tab. I am using react hooks and the component is a functional component. Also, I am new to react hooks.
Issue:
When I try to search on the 2nd dropdown, I expect the onChangeText function of the 2nd dropdown to fire but it fires the function of the 1st dropdown.
Source arrays:
const allYards = [{ id: "1", name: "Java" }, { id: "2", name: "React" }, { id: "3", name: "Angular" }];
const [yards, setYards] = useState(allYards);
const allTrucks = [{id: "1", name: "Truck 1"}, {id: "2", name: "Truck 2"}, {id: "3", name: "Truck 3"}]
const [trucks, setTrucks] = useState(allTrucks);
Render View code:
<View style={[styles.cardWrap, { padding: 30 }]}>
{assignTo === 'yard' ?
<>
<View style={[styles.inputGrp, { marginBottom: 30 }]}>
<Text style={[styles.inputLabel]}>Yard</Text>
<AutocompleteDropdown
ref={selectYardRef}
controller={(controller) => {
dropdownController.current = controller
}}
inputHeight={44}
debounce={600}
dataSet={yards.map((m) => ({
id: m.id,
title: m.name,
}))}
onChangeText={searchYards}
useFilter={false}
onSelectItem={(item) => {
console.log('selectedYard', item);
if (item?.id) {
setSelectedYard(item.id);
}
}}
textInputProps={{
placeholder: 'Choose the yard',
style: styles.autoInput,
}}
inputContainerStyle={styles.autoInputContainer}
containerStyle={{}}
rightButtonsContainerStyle={{
backgroundColor: '#fff',
}}
ClearIconComponent={<IconClear />}
ChevronIconComponent={<IconCaret />}
showChevron={true}
onClear={() => {
setSelectedYard(undefined);
}}
onFocus={handleOnFocus}
renderItem={(item, text) => (
<Text style={{ color: '#000', padding: 15 }}>
{`${item.title}`}
</Text>
)}
ItemSeparatorComponent={() => null}
/>
</View>
<View style={[styles.inputGrp]}>
<Text style={[styles.inputLabel]}>Address</Text>
<Text style={[styles.labelValue, { width: '50%' }]}>
123 Name Street
City, ST 00000
</Text>
</View>
</>
:
<View style={[styles.inputGrp, { marginBottom: 30 }]}>
<Text style={[styles.inputLabel]}>Truck</Text>
<AutocompleteDropdown
ref={selectTruckRef}
controller={(controller) => {
dropdownController.current = controller
}}
inputHeight={44}
debounce={600}
dataSet={trucks.map((m) => ({
id: m.id,
title: m.name,
}))}
onChangeText={searchTrucks}
useFilter={false}
onSelectItem={(item) => {
console.log('selectedYard', item);
if (item?.id) {
setSelectedTruck(item.id);
}
}}
textInputProps={{
placeholder: 'Choose the truck',
style: styles.autoInput,
}}
inputContainerStyle={styles.autoInputContainer}
containerStyle={{}}
rightButtonsContainerStyle={{
backgroundColor: '#fff',
}}
ClearIconComponent={<IconClear />}
ChevronIconComponent={<IconCaret />}
showChevron={true}
onClear={() => {
setSelectedTruck(undefined);
}}
onFocus={handleOnFocus}
renderItem={(item, text) => (
<Text style={{ color: '#000', padding: 15 }}>
{`${item.title}`}
</Text>
)}
ItemSeparatorComponent={() => null}
/>
</View>}
</View>
On change handler functions:
const searchTrucks = (searchText: string) => {
console.log("[~]Inside searchTrucks...");
if(searchText){
const regex = new RegExp(searchText, 'i');
const filteredTrucks = trucks.filter(truck => regex.test(truck.name));
setTrucks(filteredTrucks.slice(0, 5)); //Show only 1st 5 matches.
}
else{
setTrucks(allTrucks);
}
}
const searchYards = (searchText: string) => {
console.log("[~]Inside searchYards...");
if(searchText){
const regex = new RegExp(searchText, 'i');
const filteredYards = yards.filter(yard => regex.test(yard.name));
setYards(filteredYards.slice(0, 5)); //Show only 1st 5 matches.
}
else{
setYards(allYards);
}
}
i have a flatList that renders a component with some props, but the renderItem returns me 'undefined'. I´m new to react-native and I cant´t find a solution. Thanks
edit:
Is it possible that the styles I used in 'posts.js' may affect the flatList render?
Feed.js:
export default function Feed() {
const Posts = [
{ id: 1, title: "eu", photoDesc: 'eu' },
{ id: 2, title: "me", photoDesc: 'me' }
]
console.log;
return (
<FlatList
keyExtractor={props => props.id}
data={Posts}
renderItem={({ item }) => <FeedPosts title={`${item.title}`} photoDesc={`${item.photoDesc}`} ></FeedPosts>}
>
</FlatList>
);
}
Posts.js:
export default function FeedPosts(props) {
return (
<Container>
<Header>
<TouchableOpacity>
<FontAwesome5 name='bell' size={40} style={{ marginLeft: 10 }}></FontAwesome5>
</TouchableOpacity>
<TouchableOpacity>
<Ionicons name='add-circle' size={40} style={{ marginRight: 5 }}></Ionicons>
</TouchableOpacity>
</Header>
<Body>
<Time>15/12/2021 as 17:42pm</Time>
<User>
<Icon source={require('../../assets/vibe.jpg')}></Icon>
<Description>{props.title}</Description>
</User>
<Content>
<PetPhoto source={props.postImg}></PetPhoto>
</Content>
<ContentDesc >
<PhotoDesc> {props.photoDesc}</PhotoDesc>
</ContentDesc>
<Bottom>
<Comment title="Comment" placeholder="Escrever Comentário"></Comment>
</Bottom>
<Buttons></Buttons>
</Body>
</Container>
);
}
Your variable Posts contains an array of React components. Instead, it should contain an array of data that you transform into components.
So your Posts should look more like this:
const Posts = [
{title: "My title", photoDesc: "Desc"},
{title: "My title2", photoDesc: "Desc2"},
{title: "My title3", photoDesc: "Desc3"}
]
Here's an example (straight from the React Native documentation) of how this works in context:
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const App = () => {
const renderItem = ({ item }) => (
<Item title={item.title} />
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
}
(https://reactnative.dev/docs/flatlist)
You can see in the above example that DATA is an array of objects, which gets transformed with the function renderItem into components. Very similar to your use case.
I'm trying to figure out how to use const objects to create 3 categories in my trivia game. I'm defining each one of them like this:
const questions = [
{
question: "Qual o tipo de arquitetura utilizada na Igreja da Madre de Deus?",
answers: [
{ id: "1", text: "Colonial" },
{ id: "2", text: "Maneirista" },
{ id: "3", text: "Gótico" },
{ id: "4", text: "Barroco", correct: true }
]
},
{
question: "No século XIX, o pintor que pintou os painéis da igreja foi:",
answers: [
{ id: "1", text: "Sebastião Canuto da Silva Tavares", correct: true },
{ id: "2", text: "Frans Janszoon Post" },
{ id: "3", text: "Oscar Pereira da Silva" },
{ id: "4", text: "João de Deus Sepúlveda" }
],
quiz_answer: "Esse é o cara!"
}
]
export default questions;
There is a file called IndexQuiz, where I'm calling them through a menu of categories (inside TouchableOpacity):
export default ({ navigation }) => (
<ScrollView>
<SafeAreaView style={{alignItems: "center", flexDirection: "column"}}>
<TouchableOpacity onPress={() =>
navigation.navigate("Quiz", {
title: "Arquitetura",
questions: arquitetura,
color: "rgb(32, 53, 70)"
})}
style={DesafiosStyles.cardContainer}>
</TouchableOpacity>
<TouchableOpacity onPress={() =>
navigation.navigate("Quiz", {
title: "Curiosidades",
questions: curiosidades,
color: "rgb(32, 53, 70)"
})}
style={DesafiosStyles.cardContainer}>
</TouchableOpacity>
<TouchableOpacity onPress={() =>
navigation.navigate("Quiz", {
title: "História",
questions: historia,
color: "rgb(32, 53, 70)"
})}
style={DesafiosStyles.cardContainer}>
</TouchableOpacity>
</SafeAreaView>
</ScrollView>
);
But when it comes to the Quiz file, inside render I have this:
render() {
const questions = this.props.route.params.questions.length;
const question = questions[this.state.activeQuestionIndex];
//console.log(question);
return (
<View
style={[
styles.container,
{ backgroundColor: this.props.route.params.color }
]}
>
<StatusBar barStyle="light-content" />
<SafeAreaView style={styles.safearea}>
<View>
<Text style={styles.text}>{question.question}</Text>
<ButtonContainer>
{answers.map(answer => (
<Button
key={answer.id}
text={answer.text}
onPress={() => this.answer(answer.correct)}
/>
))}
</ButtonContainer>
</View>
<Text style={styles.text}>
{`${this.state.correctCount}/${this.state.totalCount}`}
</Text>
</SafeAreaView>
<Alert
correct={this.state.answerCorrect}
visible={this.state.answered}
/>
</View>
);
}
Every time I try to call any of these categories, I got the "undefined is not an object" exception. I've tried to import the files and the "questions" const itself, but it didn't work. As simple as that must be, I'm stuck in this (yep, I'm kinda slow and basically a newbie with react native lol):
<Text style={styles.text}>{question.question}</Text>
<ButtonContainer>
{answers.map(answer => (
<Button
key={answer.id}
text={answer.text}
onPress={() => this.answer(answer.correct)}
/>
))}
</ButtonContainer>
Without this code, it shows the counter: "this.state.correctCount}/${this.state.totalCount", but that's all. How can I call these questions and answers properly?
I think the problem is that you try to get questions from length property, not from questions object itself:
const questions = this.props.route.params.questions.length;
const question = questions[this.state.activeQuestionIndex];
Hello I am new in react native. I am working on flatlist I want multiple items to be shown in list in one container. Example I want to add multiple data in one container. My code is given below any help will be appreciated.
this.state = {
FlatListItems: [
{ key: "Skptricks" },
{ key: "Sumit" },
{ key: "Amit" },
{ key: "React" },
{ key: "React Native" },
{ key: "Java" },
]
};
and the I have print the key.
<View style={styles.container}>
<FlatList
data={ this.state.FlatListItems }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) =>
<Text style={styles.item} onPress={this.GetItem.bind(this, item.key)} >
{item.key} </Text>
}
/>
</View>
i want this kind of layout i have flatlist i want to show thw data like this given in image.
Modify state as below, add more items similar to data & key
this.state = {
FlatListItems: [
{ key: "Skptricks", data: "one" },
{ key: "Sumit" , data: "two"},
{ key: "Amit" , data: "three"},
{ key: "React", data: "four" },
{ key: "React Native" , data: "five"},
{ key: "Java", data: "six" },
]
};
And render it inside the FLatlist as :
<View style={styles.container}>
<FlatList
data={ this.state.FlatListItems }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) =>(
<View>
<Text style={styles.item} onPress={this.GetItem.bind(this, item.key)} >
{item.key} </Text>
<Text {item.data} </Text>
</View>
)}
numColumns={2}
keyExtractor={(item, index) => index}
/>
</View>
just add them as as keys in your sample array of objects. and access them in item in your FlatList component.
FlatListItems: [
{ title: "Skptricks",subTitle:"Asdasd" },
{ title: "melons",subTitle:"melons are great" }
]
and in your FlatList component
<FlatList
data={ this.state.FlatListItems }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) =>
(<View>
<Text style={styles.item} onPress={this.GetItem.bind(this, item.key)} >
{item.title} </Text>
<Text style={styles.item} onPress={this.GetItem.bind(this, item.key)} >
{item.subTitle} </Text>
</View> )
}
keyExtractor={(item,index)=>index}
/>
Edit: give the numColumns prop to FlatList Component as
numColumns={2}
I'd like to put a title in the Alert.alert() and display the data under the title.
I'd appreciate it if you could tell me where the problem is and how to solve it.
import React, { Component } from "react";
import {
TouchableOpacity,
Text,
View,
ListView,
TouchableHighlight,
Dimensions,
Image,
Animated,
StyleSheet,
TextInput,
ImageBackground,
Alert,
FlatList
} from "react-native";
import { SearchBar, ListItem, List } from "react-native-elements";
import Ionicons from "#expo/vector-icons/Ionicons";
import sitterdata from "../components/sitterdata";
const { width, height } = Dimensions.get("window");
/*
const datas = [
{
name: "Registers",
route: "Registers",
icon: "phone-portrait",
bg: "#C5F442"
},
{
name: "PetSitters",
route: "PetSitters",
icon: "easel",
bg: "#C5F442"
}
];
*/
export default class PetSitters extends Component {
constructor(props) {
super(props);
this.state = {
data: sitterdata,
refreshing: false
};
}
static navigationOptions = ({ navigation }) => {
return {
title: "Pet Sitters",
headerLeft: (
<TouchableOpacity
style={{ padding: 5, paddingRight: 15 }}
//dataArray={datas}
onPress={() => navigation.openDrawer()}
>
<Ionicons name={"ios-menu"} size={35} color={"#fff"} />
</TouchableOpacity>
),
headerRight: (
<TouchableOpacity
style={{ padding: 5, paddingRight: 15 }}
onPress={() => navigation.navigate("Add")}
>
<Ionicons name={"ios-add"} size={35} color={"#fff"} />
</TouchableOpacity>
)
};
};
showAlert(navigation) {
Alert.alert(
"이 펫시터와 거래 하시겠습니까?",
// this.item.bind(sitterdata.by),
//"데이터 입력",
this.state.data(sitterdata.by),
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{ text: "OK", onPress: () => navigation.navigate("Add") }
],
{ cancelable: false }
);
}
async filterSearch(text) {
const newData = sitterdata.filter(function(item) {
const itemData = item.address.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
await this.setState({
data: newData,
text: text
});
}
refreshData = () => {};
renderItem = ({ item }) => {
return (
<TouchableHighlight style={styles.containerCell}>
<View>
<TouchableOpacity
onPress={() => this.showAlert(this.props.navigation)}
>
<Image
style={{
width: width,
height: 180,
resizeMode: "stretch"
}}
source={{ uri: item.image }}
/>
</TouchableOpacity>
<View style={styles.footerContainer}>
<View style={styles.imageUser}>
<Image style={styles.imageAvatar} source={{ uri: item.user }} />
</View>
<View style={styles.footerTextContainer}>
<Text style={styles.text}>{item.introduce}</Text>
<Text style={[styles.text, styles.textTitle]}>
{item.address}
</Text>
<Text style={[styles.text, styles.textBy]}>By {item.by}</Text>
</View>
</View>
</View>
</TouchableHighlight>
);
};
render() {
return (
<View style={styles.container}>
<Animated.View
style={[
styles.content,
{
width: width,
backgroundColor: "#dfe4ea",
flex: 1,
transform: [
{
perspective: 450
}
]
}
]}
>
<SearchBar
onChangeText={text => this.filterSearch(text)}
placeholder={"여기에 입력하세요"}
value={this.state.text}
lightTheme
containerStyle={{}}
/>
<FlatList
style={styles.listContainer}
onRefresh={this.refreshData}
renderItem={this.renderItem}
refreshing={this.state.refreshing}
data={this.state.data}
keyExtractor={(item, index) => item.address}
/>
</Animated.View>
</View>
);
}
}
The code above is the entire code, and the error is generated by the data representation under the title in Alert.alert().
I think it's a matter of how the Alert.alert data is expressed, but I can't find out which part is wrong.
showAlert(navigation) {
Alert.alert(
"이 펫시터와 거래 하시겠습니까?",
// this.item.bind(sitterdata.by),
//"데이터 입력",
this.state.data(sitterdata.by),
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{ text: "OK", onPress: () => navigation.navigate("Add") }
],
{ cancelable: false }
);
}
The code above is an Alert.alert() function that I am failing.
enter image description here
export default (sitterdata = [
{
id: 1,
image:
"https://postfiles.pstatic.net/MjAxOTAxMTVfMjk3/MDAxNTQ3NTEzMDI1MDEx.ODD9YUUNc5YSk4Zz1wTgxmpf_BRr154ekJ-vJQ1f3ocg.u1uIXInfJ3O2PTKFmKFaI46epH_e8IzD5TEB96K-eF4g.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.42.43.png?type=w966",
introduce: "강아지 전문 펫시터에요 잘부탁드립니다",
address: "평택시 서정동",
user:
"https://postfiles.pstatic.net/MjAxOTAxMTVfOTQg/MDAxNTQ3NTEyODU0NDk4.DcAvlx3CGY9pGFlgWZA7mIr6_SCt8h_gGaHYGAFlDIYg.bQ9kBiykOzlbxyIyQ3nTCO7lGw4NVmmIeDV7pz0OX94g.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.28.54.png?type=w966",
by: "수지"
},
{
id: 2,
image:
"https://postfiles.pstatic.net/MjAxOTAxMTVfMTMx/MDAxNTQ3NTEzMDMzMDgx.SbY_nsX7oK4UlZGzre6U5dLHinRfCoAYyvnSzXuZR7cg.5K3sX7E0bDpgyzDifD174hfQBOnJDtLVFqTe8BHH7Gcg.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.42.57.png?type=w966",
introduce: "나의 반려견은 편안하고 주인님은 안심할 수 있게",
address: "서울특별시 서초구",
user:
"https://postfiles.pstatic.net/MjAxOTAxMTVfMjU2/MDAxNTQ3NTEyODY3MTE2.X4LDN12uIgRkOFrUChl0s9UnKiu9VOPEOkWbIRHPDpgg.DrmXUbVURwsTuGs5dlOL_wugRf1nnANxWSIN4jYkdX0g.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.29.23.png?type=w966",
by: "손예진"
},
{
id: 3,
image:
"https://postfiles.pstatic.net/MjAxOTAxMTVfOTIg/MDAxNTQ3NTEzMDM3MDAy.p_CNMU7vlCaELYpfuqf6H9GrCEPe9BzFdeNojFuKGc4g.65lwFvImqL2QgC01mNPzIUbY0tgBz4lukZplv9NZkJAg.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.43.14.png?type=w966",
introduce: "밍밍이와 함꼐하는 좋은 친구들 :-)",
address: "대전광역시 유성구",
user:
"https://postfiles.pstatic.net/MjAxOTAxMTVfMjY4/MDAxNTQ3NTEzMDE5MDI2.fmBkO0W8lFwWCzo3KrJ3EDkTTZ_NmAKH0wlF050XMcYg.GJ8JTbs5nQNosj1ZhkK-1lm-ah2LIAN7i_d3hjIQ4K8g.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.42.09.png?type=w966",
by: "문채원"
}
]);
add Data code
showAlert(navigation) {
Alert.alert(
"이 펫시터와 거래 하시겠습니까?",
// this.item.bind(sitterdata.by),
//"데이터 입력",
item.by,
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{ text: "OK", onPress: () => navigation.navigate("Add") }
],
{ cancelable: false }
);
}
async filterSearch(text) {
const newData = sitterdata.filter(function(item) {
const itemData = item.address.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
await this.setState({
data: newData,
text: text
});
}
refreshData = () => {};
renderItem = ({ item }) => {
return (
<TouchableHighlight style={styles.containerCell}>
<View>
<TouchableOpacity
onPress={() => this.showAlert(this.props.navigation, item)}
>
<Image
style={{
width: width,
height: 180,
resizeMode: "stretch"
}}
source={{ uri: item.image }}
/>
</TouchableOpacity>
<View style={styles.footerContainer}>
<View style={styles.imageUser}>
<Image style={styles.imageAvatar} source={{ uri: item.user }} />
</View>
<View style={styles.footerTextContainer}>
<Text style={styles.text}>{item.introduce}</Text>
<Text style={[styles.text, styles.textTitle]}>
{item.address}
</Text>
<Text style={[styles.text, styles.textBy]}>By {item.by}</Text>
</View>
</View>
</View>
</TouchableHighlight>
);
};
Corrected the answer but item not found.
You don't need to access the this.state.data inside your showAlert function you could actually pass the item to the function and use that. I would update your showAlert function to the following
showAlert(navigation, item) {
Alert.alert(
"이 펫시터와 거래 하시겠습니까?",
// this.item.bind(sitterdata.by),
//"데이터 입력",
item.by,
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{ text: "OK", onPress: () => navigation.navigate("Add") }
],
{ cancelable: false }
);
}
As you are creating the link to the showAlert function inside the renderItem function I would just pass the item that you are using to that function.
So your renderItem now would look like
renderItem = ({ item }) => {
return (
<TouchableHighlight style={styles.containerCell}>
<View>
<TouchableOpacity
onPress={() => this.showAlert(this.props.navigation, item)} // here we now pass the item
>
<Image
style={{
width: width,
height: 180,
resizeMode: "stretch"
}}
source={{ uri: item.image }}
/>
</TouchableOpacity>
<View style={styles.footerContainer}>
<View style={styles.imageUser}>
<Image style={styles.imageAvatar} source={{ uri: item.user }} />
</View>
<View style={styles.footerTextContainer}>
<Text style={styles.text}>{item.introduce}</Text>
<Text style={[styles.text, styles.textTitle]}>
{item.address}
</Text>
<Text style={[styles.text, styles.textBy]}>By {item.by}</Text>
</View>
</View>
</View>
</TouchableHighlight>
);
};