How to display a single dimensional array in FlatList - javascript

You would think that this would be the easiest thing in the world to find an example of but everthing I found online has always had a JSON file as the data source so there are keys to reference
stuff like this...eg item.name etc
const list = [
{
name: 'Amy Farha',
subtitle: 'Vice President'
},
{
name: 'Chris Jackson',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
subtitle: 'Vice Chairman'
},
... // more items
]
keyExtractor = (item, index) => index.toString()
renderItem = ({ item }) => (
<ListItem
title={item.name}
subtitle={item.subtitle}
leftAvatar={{
source: item.avatar_url && { uri: item.avatar_url },
title: item.name[0]
}}
/>
)
My data source is just a plain single dimension array, no keys or identifiers of any kind. The data is what it is and wont be changed
data = ['value1','value2','value3',...]
The code I have so far (which obviously doesnt work) is
import React, { Component } from 'react'
import { FlatList, ListItem } from 'react-native'
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<ListItem
key={item.id}
/>
)}
/>
Im guessing I need to use the keyExtractor somewhere to generate an id but how do I reference the actual values in the data to display them if it doesnt have an identifier in the data like a json would?

Try this:
<FlatList
data={this.state.data}
keyExtractor={item => item}
renderItem={({ item }) => (
<ListItem
title={item}
/>
)}
/>
const ListItem = ({ title }) => (
<View>
<Text>{title}</Text>
...
</View>
);

Related

display image and text from array on react native

I'm new on react native. I want to display images and text from array.
When I'm trying to extract image from my app, It doesn't work, the images are not displayed.
const DATA = [
{
title: "Animaux",
data: ["Poissons","Crevettes","Escargots"],
image: [require('../assets/icon_aquarium_style.png'),require('../assets/icon_aquarium_style.png'),require('../assets/icon_aquarium_style.png')]
}
];
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const ImageType = ({ image }) => (
<View style={styles.image}>
<Image source={image}/>
</View>
);
export default class InventaireScreen extends React.Component {
render() {
return (
<SafeAreaView style={styles.container}>
<SectionList
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item, image }) =>
<View >
<ImageType source={image}/>
<Item title={item} />
</View>
}
renderSectionHeader={({ section: { title } }) => (
<View>
<Text>{title}</Text>
</View>
)}
/>
</SafeAreaView>
);
}
}
the images are not displaying.
Could you please tell me where I'm wrong ?
Thanks.
EDIT :
I modified my array like that :
const DATA = [
{
title: "Poissons",
image: require('../assets/icon_aquarium_style.png')
},
{
title: "Crevettes",
image: require('../assets/icon_aquarium_style.png')
},
{
title: "Escargots",
image: require('../assets/icon_aquarium_style.png')
},
];
I try to extract data using render:
export default class InventaireScreen extends React.Component {
render() {
return (
<SafeAreaView style={styles.container}>
<SectionList
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) =>
<View style={{flexDirection: 'row', textAlign: 'left', fontSize: 15, backgroundColor:'white'}}>
<ImageType image={item.image}/>
<Item title={item.data} />
</View>
}
renderSectionHeader={({ section: { title } }) => (
<View>
<Text style={styles.header}>{title}</Text>
</View>
)}
/>
</SafeAreaView>
);
}
}
I want to display section title using title parameter, an image using image source, and a text using data parameter of my array.
I have this error
ERROR TypeError: undefined is not an object (evaluating 'items.length')
``
In Your Statement
renderItem={({ item, image }) =>
the second argument should be index,
Instead of 'image' it should be 'index'
renderItem={({ item, index }) =>
In order to fetch parameter 'image' from your array you will need to change your code like below :
<View >
<ImageType image={item.image}/>
<Item title={item.title} />
</View>
you data object should be an array of objects to map through it, like
var Data = [{title:"Poissons",image:require('../assets/icon_aquarium_style.png')},{title:"Crevettes",image:require('../assets/icon_aquarium_style.png')},{...},{...}]
and then in render item
{({ item }) =>
<View >
<ImageType image={item.image}/>
<Item title={item.title} />
</View>
}
Try correcting renderItem.
renderItem={({ item }) =>
<View >
<ImageType image={item.image}/>
<Item title={item.title} />
</View>
}
and keyExtractor.
keyExtractor={(item, index) => item.title + index}
this keyExtractor will only take the title and index instead of the full object.
and data format.
const DATA = [
{
title: "Poissons",
image: require('../assets/icon_aquarium_style.png')
},
{
title: "Crevettes",
image: require('../assets/icon_aquarium_style.png')
},
{
title: "Escargots",
image: require('../assets/icon_aquarium_style.png')
},
];

Flat list does not show in other component

Flat list does not show in react native. I want to pass information to another component, I'm rendering using flatList, but nothing appears on the screen and I don't get the error ... is my other component that will receive the information
my flatList :
return (
<View style={styles.container}>
<FlatList
numColumns={2}
data={DATA}
renderItem={({item}) => {<Item {...item} />}}
keyExtractor={(item) => item.id}
ListHeaderComponent={<Cabecalho />}
/>
</View>
);
};
MY COMPONENT WHAT SHOULD YOU RENDER
export const Item = ({titulo}) => {
return (
<View>
<Text >{titulo}</Text>
</View>
);
}
DATA:
export const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
titulo: 'Abajur',
imagem: require('../assets/images/01-tablelamps.png'),
estudio: 'Jim&Jill Designs',
itemName: 'Wilson',
preco: 92.1,
itemDesc:
'Contrary to popular belief, Lorem Ipsum is not simply random text',
},
it's happened because renderItems doesn't return any component to fix this change
renderItem={({item}) => {<Item {...item} />}}
to
renderItem={({item}) => {return <Item {...item} />}}
or
renderItem={({item}) => <Item {...item} />}

VirtualizedList: missing keys for items - React Native

On my componentDidMount() I do a Query where I receive some documents from a MongoDb database which I want to show in a FlatList. When I have received the results from the Query I map them to my state.list with the function mapToList() The list.id I use here is an inserted document _id generated by MongoDb itself. Just to have a id to work with here. Then I add key={item.id} to my renderItem({item}) method, but I still get the error that I have to add keys to my VirtualizedList or use a KeyExtractor.
I'm trying to delete an item from the FlatList with the use of Swipeout but first I have to get this id thing to work.
export default class MyFlatList extends React.Component{
state={
loading: false,
list: [{
name: '',
subtitle: '',
rightSubtitle: '',
rightTitle: '',
id: undefined
}]
};
mapToList();
mapToList(result)
{
const list = [];
for(var i = 0; i<result.length; i++)
{
list[i] = {name: result[i].name,
subtitle : result[i].projectname,
rightTitle : result[i].work,
rightSubtitle : result[i].date,
id: result[i]._id
};
}
this.setState({list});
}
render()
render(){
return(
<View>
<FlatList
data={this.state.list}
renderItem={this.renderItem}
/>
<ActivityIndicator animating={this.state.loading} color="black" size="large"/>
</View>
)
}
renderItem({item})
renderItem = ({item}) => (
<Swipeout right={swipeoutBtns}>
<ListItem
title={item.name}
key={item.id}
titleStyle={styles.titleText}
subtitleStyle={styles.subtitleText}
rightTitleStyle={styles.rightSubtitleText}
rightSubtitleStyle={styles.rightSubtitleText}
rightIcon={
<Icon name="keyboard-arrow-right"
size={17}
color="black"
/>}
subtitle={item.subtitle}
rightTitle={item.rightTitle}
rightSubtitle={item.rightSubtitle}
leftAvatar={{rounded:false, title:'PS'}}
/>
</Swipeout>
)
You need keyExtractor parameter. As default it will check if the item has a key property which you don't that why you are getting this warning.
Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item.key, then falls back to using the index, like React does.
Do this:
_keyExtractor = (item, index) => item.id.toString();
<FlatList
data={this.state.list}
renderItem={this.renderItem}
keyExtractor={this._keyExtractor}
/>

How to dynamically set react-native image source inside flat list

I'm new to react native i'm trying to populate flat list with images. All the images are stored inside the app. I want to set image source dynamically in every iteration. This is what I tried. Please help me.
<FlatList
data={this.state.listData}
renderItem={({ item }) => {
<Image
source={
(item)=>{
switch(item.TypeX){
case '1':
return require('path 1');
case '2':
return require('path 2')
}
}} />
}
</FlatList>
You should have images in the data .. in your case in listDate
state = {
listData: [
{...,image:require('1.png')},
{...,image:require('2.png')}
...
]
}
Then in your render function
<FlatList
data={this.state.listData}
renderItem={({ item }) => {
<Image
source={item.image}
}} />
}
</FlatList>
If you have the images stored in remote url then your state should look like
state = {
listData: [
{...,image: 'https://somedomain.com/imagename.png'},
{...,image: 'https://somedomain.com/imagename2.png'}
...
]
}
and in your render function you should use following code
<FlatList
data={this.state.listData}
renderItem={({ item }) => {
<Image
source={{uri: item.image}}
}} />
}
</FlatList>
If you are fetching record from the api you place the request in componentDidMount react callback and set the data using setState function
I think putting switch inside image source prop is not a good idea. Also not sure whether it will work or not. But, you can do one thing..when you are getting data from API that you are filling in your listData array you can append your images' url/path just after getting data from API
for eg you receive an array of objects in response:
res=[ { data1:'', data2:''.. },{ data1:'', data2:''.. },{ data1:'', data2:''.. },{
data1:'', data2:''.. }];
so you can iterate the this array and append the images like this:
res.map((obj, i) => {
let path = imagepPathArray[i];
return {...obj, imagePath: path
}
})
and access image path like this in FlatList:
renderItem={({ item }) => {
<Image
source={{uri: item.imagePath}}
}}
PS: store image paths in separate array first.
I found a soliution ,
we can create simple function like below in our componet
getFanSpeedImage(speed) {
switch (speed) {
case '1':
return (<Image style={styles.statusButton} source={require('1.png')} />);
case '2':
return (<Image style={styles.statusButton} source={require('2.png')} />);
case '3':
return (<Image style={styles.statusButton} source={require('3.png')} />);
}
}
after that we can call it in out main render function like below
render(){
return(
<FlatList
data={this.state.listData}
renderItem={({ item }) => {
{this.getFanSpeedImage(item.typeX)}
}
</FlatList>
);
}
Whenever you have to display images while using Flatlist its good practice if you keep them in an array which you pass as a data to the Flatlist
Hence, first of all, try to structure your data as follows.
const data = [{
id: 1,
name: 'Pikachu',
image: require('./path/pikachu.png'),
},
{
id: 2,
name: 'One Plus',
image: require('./path/onPlus.png'),
},
{
id: 3,
name: 'Hero Go Pro',
image: require('./path/goPro.png'),
},
]
Note the require keyword in the data this will automatically import the required images and now we pass this data to the Flatlist as follows
<FlatList
showsVerticalScrollIndicator={false}
data={data}
renderItem={({item}) => <MyComponent data={item} />}
keyExtractor={item => item.id}
numColumns={2}
/>
Now that we have passed the data to <MyComponent/> it will be accessible in the same component and we can do the following to use it to display the image
<Image source={this.props.data.image} style={{height:20, width:20}}/>
Hope this helps
You can also use https://www.npmjs.com/package/react-native-placeholderimage library.This library helps to put placeholder until your image is not downloaded from internet or API.
renderItem={({item}) =>
<PlaceHolderImage
source={!!data.imageurl ? { uri: imgURL } : AppImages.placeHolderImage.source}
style={iconStyle}
placeHolderURI={AppImages.placeholderImage.source}
/>
}

How to handle flatlist item data in react-native?

I'm using React-native Flat List in which i have passed sorted array into data props.Now i want to show items according to date
MY code :
<FlatList
horizontal={true}
keyExtractor={(item, index) => index.toString()}
data={this.state.Data}
renderItem={({ item }) =>
<View>
<Image source = {{uri: item.image}}/>
<Text>{item.date}</Text>
</View>
}
/>
I want my image show according to item.date.For example :
Date - 20-09-2018
Image1 ..Image 2...
Date - 21-09-2018
Image1..Image2 ...
Help me !!
You can use SectionList for this purpose as it provides good API for handling such cases.
<SectionList
style={{ flex: 1 }}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderItem}
renderSectionHeader={this.renderSectionHeader}
sections={list || []}
ItemSeparatorComponent={this.renderSeparator}
/>
For that you need to map your data and create something like an array of objects as
[
{
heading: 'Date - 20-09-2018',
data: [Image1, Image2]
},
{
heading: 'Date - 21-09-2018',
data: [Image1, Image2]
}
]
So the renderSectionHeader function will be something like:
renderSectionHeader = ({section}) => {
return (
<View>
<Text>{section.heading}</Text>
</View>
)
}
And all the other functions like renderItem, renderSeparator etc. you can define as you want.
Check this link for more info

Categories