How do i display card with different items when key pass through navigator in react native - react-native

When pass the item to the next screen through navigator of radio.js the other screen attendence.js card shows all item details with same id in the card with multiple times when an C# API is called in attendancjs.
I want to show different items in the card when calling an API in attendance.js.
Radio.Js
onRadioBtnClick = () => {
data.map((item) =>
{
if(item.attendanceType==checked)
{
// if (index < item) {
// console.log(item)
// return item;
// }
// for(i=0;i<item.length;i++)
// {
// elements=item[i]
console.log({item})
// }
navigation.navigate('attendance',{item})
} }
);
enter image description here
Attendance.js
return (
<ScrollView>
{
// {`${post.attendanceTime}`+ `${post.attendanceType}`}
// console.log(item)
data.map(() => (
<View style={styles.view} >
<Card style={styles.cardWrapper} >
<View style={styles.card}>
<Text style={styles.title}>Key:{item.id} {'\n'}
Latitude:{item.latitude} {'\n'} Longitude:{item.longitude}{'\n'}
Attentance Time:{item.attendanceTime} {'\n'}
Attentance:{`${item.attendanceType}`}{item.attendanceType=="i"? (<Image style={styles.icon} source={require('../assests/checked.png')} /> ):(<Image style={styles.icon} source={require('../assests/delete.png')} />)}
{'\n'}
Employee Name: {item.userInfo.displayName}
</Text>
</View>
</Card>
</View>
))

You are passing object navigation.navigate('attendance',{item}) from Radio.js and in Attendance.js you are iterate over data array and display only item(which is one object) to length of data. So it will take length of data and display one item which is passed from Radio.js

Related

React Native FlatList key with multiple rendering

I'm trying to render multiple components via FlatList but i get this error : "Warning: Each child in a list should have a unique "key" prop."
I made sure the keyExtractor property was set up correctly but i believe my issue happened when trying to render multiple components inside my FlatList with map.
My FlatList and custom component looks like so :
const ItemView = (row: any) => {
let title = row.item.title
let split = title.split(search)
let searchStringCount = split.length
return (
<Text>
{
split.map((elem: string, index: number) => {
return (
<>
<Text style={styles.textListStyle}>
{elem}
</Text>
{index + 1 < searchStringCount &&
<Text style={styles.textHighLightStyle}>
{search}
</Text>}
</>
)
})
}
</Text>)
}
<FlatList
style={styles.itemStyle}
data={filteredData}
keyExtractor={(item, index) => {
return index.toString();
}}
ItemSeparatorComponent={ItemSeparatorView}
renderItem={ItemView} />
I've tried in vain inserting manually a key property to the generated Text components.
you need to add key prop when render with map
split.map((elem: string, index: number) => {
return (
<View key={index}>
<Text style={styles.textListStyle}>
{elem}
</Text>
{index + 1 < searchStringCount &&
<Text style={styles.textHighLightStyle}>
{search}
</Text>}
</View>
)
})

Is there a way to get the Title of the selected item from another component in React Native

I have two different components "HomePage" & "ListItemCA"
In HomePage, I have a FlatList and a modal popup
<FlatList
data={ listData}
keyExtractor={list => list.Title}
renderItem={({ item }) => <ListItemCA data={item} onLongPress={openModal} />}
/>
and each list item is called from another component ListItemCA
function ListItemCA({data, onLongPress}) {
return (
<TouchableOpacity onLongPress={onLongPress} >
<View style={styles.container}>
<Text style={styles.title}>{data.Title}</Text>
<View style={styles.metaContainer}>
<Text style={styles.meta}>{( data.totalMonths != null ? data.totalMonths : '0' )} Months</Text>
<Text style={styles.meta}>{( data.members != null ? data.members.length : '0' )} Members</Text>
</View>
</View>
</TouchableOpacity>
);
}
What I want to acheive?
I want to get the selected list item title on my HomePage component. When a user longpress on a list item that title should be displayed on a modal popup. How do I pass the selected list item title to the HomePage component using longpress?
If your goal is to display data from the long pressed item in the modal, you could add the data as a parameter of your openModal function:
function openModal(data) {
// your function
return (
<Text>{data.Title}</Text>
)
}
Then, in your FlatList, modify the props of ListItemCA to call openModal for the selected item:
renderItem={({ item }) => <ListItemCA data={item} onLongPress={openModal(item)} />}
If you also want to save the data from the long pressed item in your HomePage component for other uses, you could save it in the state. In your HomePage component:
import React, { useState } from 'react'
function HomePage() {
const [itemData, setItemData] = useState()
// your code
}
Then, in your flatlist:
<FlatList
data={listData}
keyExtractor={list => list.Title}
renderItem={({ item }) =>
<ListItemCA
data={item}
onLongPress={ () => {
setItemData(item)
openModal(item)
}}
/>
}
/>
You can achieve this by passing(return) parameter from your component like this -
function ListItemCA({data, onLongPress}) {
return (
<TouchableOpacity onLongPress={() => {
onLongPress(data.Title);
//return data.Title when onLongPressed clicked
}}>
<View style={styles.container}>
...
</View>
</TouchableOpacity>
);
}
then get it in props -
<FlatList
data={listData}
keyExtractor={list => list.Title}
renderItem={({ item }) =>
<ListItemCA
data={item}
onLongPress={(title) => {//this **title** return from **onLongPress(data.Title)**
openModal();
setTitle(title);// or directly can pass that title in openModal func.
}}
/>
}
/>

Display nested array into a Flat list in react native

I am a newbie in RN and recently started using redux. I have a api response which is of the below format:
{
records : [
{
name : "cde"
groups :[
{
id : "212"
fields[{
data : "abc"
}]
}]
}
]
}
So, Inside records , I have an array of objects "groups" and inside "groups" I have array of objects "fields" and inside fields, I have data which I want to display inside FlatList. I am able to display "name" which is inside records inside FlatList As of now.
My File PeopleList.js looks like below :
export default class PeopleList extends Component {
_keyExtractor = item => name;
_renderItem = ({ item }) => {
const { name} = item;
const groups = this.props.people.map((items, index)=>{
return( <Text>{name}({items.id})</Text>)
})
//const {} = item.groups;
return (
<View>
<View style={styles.cardContainerStyle}>
<View style={{ paddingRight: 5 }}>
<Text style={styles.cardTextStyle}>
{/* {name} {"\n"} */}
{groups}
</Text>
</View>
<Image
style={styles.faceImageStyle}
// source={{ uri: picture.medium }}
/>
</View>
</View>
);
};
render() {
return (
<FlatList
style={{ flex: 1 }}
data={this.props.people}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
/>
);
}
}
PeopleList.propTypes = {
people: PropTypes.array
};
people is an array that contains the records object : responseJson.records
So, how can I display data and also what is the use of keyextractor?
As per what I have searched so far is that we need to use map function for arrays but not quite sure how to use it here
Edit : I have modified my code and used map func, now the output that I get is:
name1 groupid1 groupid2 ... so on
name2 groupid1 groupid2 ... so on
.
.
. and so on
where as I want :
name1 groupid1
name2 groupid2
.
.
.
You can display the data using destructuring assignment like the one you use in your code.
Eg:
const { name, groups } = item;
const { fields } = item.groups;
keyExtractor assign a unique key value to your render items. In your case, it assign a name value (from your this.props.people) to each items in your Flatlist.
As you know, all react children needs a unique key or you will get this warning
Warning: Each child in a list should have a unique "key" prop
The below code needs to be added
if(item.groups){
groupList = item.groups.map((unit, key)=>{
return (<View key="key">
<Text>{unit.id}</Text>
{ unit.fields.map((unit1, key1)=>{
return <Text key={key1}>{unit1.name}</Text>
})
}
and later we need to display groupList
return (
<View>
<View style={styles.cardContainerStyle}>
<View style={{ paddingRight: 5 }}>
<Text style={styles.cardTextStyle}>
{/* {name} {"\n"} */}
{groupList}
</Text>
</View>
<Image
style={styles.faceImageStyle}
// source={{ uri: picture.medium }}
/>
</View>
</View>
);
The above snippet will display data inside fields.

How to get the style name and state name of a clicked element in React Native?

In the following, first example how do I check if the clickable element TouchableWithoutFeedback has the style named EntryBlock1?
render() {
return (
<TouchableWithoutFeedback style={styles.EntryBlock1} onPress={() => this.CheckIfHasStyles()}>
<View style={styles.redundantWrapperNumber1}>
<Text style={styles.redundantWrapperNumber2}>Click To Test For Style</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback style={styles.EntryBlock2} onPress={() => this.CheckIfHasStyle()}>
<View style={styles.redundantWrapperNumber1}>
<Text style={styles.redundantWrapperNumber2}>Click To Test For Style</Text>
</View>
</TouchableWithoutFeedback>
); // end return
} // end render
In the 2nd example, how can I check if TouchableWithoutFeedback has the state name EntryBlock1 ?
constructor (props) {
super(props);
this.state = {
EntryBlock1: [styles.entryBlockButton, styles.entryBlockButtonMin],
EntryBlock2: [styles.entryBlockButton, styles.entryBlockButtonMax],
}
}
render() {
return (
<TouchableWithoutFeedback style={this.state.EntryBlock1} onPress={() => this.CheckIfHasStateName()}>
<View style={styles.redundantWrapperNumber1}>
<Text style={styles.redundantWrapperNumber2}>Click To Test For Style</Text>
</View>
</TouchableWithoutFeedback>
); // end return
What I've Tried
Different stuff along the lines of the following..
CheckIfHasStyles =()=> {
var object = this.state;
var stringifiedObject = JSON.stringify(object);
var slicedObject = stringifiedObject.slice(2, 13);
if (slicedObject === 'EntryBlock1') {
alert('success');
} else {
alert('failure');
}
}
.. which actually works for one very specific example, but not when I have multiple state names as this.state gets all of them in one object and not just the state of the element clicked.
Note: My question is solely about getting attributes and their values. It is to help me develop a style of toggling styles on elements but I am only looking for attribute stuff in these answers as I would like to use attributes, if possible, for more than just toggling in the future.
You can pass it as parameter to your function directly like this:
render() {
return (
<TouchableWithoutFeedback style={styles.EntryBlock1} onPress={() => this.CheckIfHasStyles('EntryBlock1')}>
<View style={styles.redundantWrapperNumber1}>
<Text style={styles.redundantWrapperNumber2}>Click To Test For Style</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback style={styles.EntryBlock2} onPress={() => this.CheckIfHasStyle('EntryBlock2')}>
<View style={styles.redundantWrapperNumber1}>
<Text style={styles.redundantWrapperNumber2}>Click To Test For Style</Text>
</View>
</TouchableWithoutFeedback>
);
}
and check if you are receiving any parameter in your function and do what you want
based on If-else condition

Active is not updating. After a hot reload it is active react native

My child component is below
export default function PickerList ({headingText,listData,hideView,finalpickedItem,onItemSelected,selected} ) {
const {modalHolder,modalHeader,modalHeaderText,modalBody,PerListView,PerListVie wText,okCancel,okCancelHolder,PerListViewActive,
} = styles;
return(
<View style={modalHolder}>
<View style={modalHeader}>
<Text style={modalHeaderText}>{headingText}</Text>
</View>
<View style={modalBody}>
<FlatList data={listData} renderItem={({item , index}) =>
<TouchableOpacity
onPress={() => {
{headingText === 'name'?
onItemSelected(item.name)
: headingText === 'Time' ?
onItemSelected(item.time)
: headingText === 'Property'
onItemSelected(item.property)
}
}}
style={{width:'100%',}}
>
<View
style={
selected===item.name ? PerListViewActive : PerListView > // here i am not getting active hot reload making it active
<Text style={PerListViewText}>
{item.name }
</Text></View>
</TouchableOpacity>
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
</View>
);
};
PickerList.propTypes = {
onItemSelected: PropTypes.func.isRequired,
};
and my parent is
onMenuItemSelected = item => {
console.log(item); // i am getting here selected item
this.setState({ commonSelected: item }); // i am getting final state also.
}
<PickerList
headingText="Property"
listData = {this.state.property_type_options}
hideView = {()=>{this.hideView()}}
finalpickedItem = {()=>{this.finalpickedItem()}}
onItemSelected={this.onMenuItemSelected}
selected = {this.state.commonSelected} /// i have final value here also
/>
issue is "selected" not working every thing is working fine .. selected working but after a hot reload. can i re-render module. state is updating fine but it is not getting active.
I found my answer this is very nice.
extraData={this.state}