Use Images from Array in flatlist - react-native

I am implementing one scenario in which I am getting data from backend but I need to show image with each item. The image will come from local asset folder. I tried to use both array with flat-list but there is issue with the same. Could anyone let me know how to resolve that.
I am not able to understand how to implement that logic.
Thanks in advance!

React Native FlatList renderItem callback get an object parameter with 3 props, item, index and separators:
renderItem({item, index, separators});
You don't have to define keys in your array, just the images sources and then use item and index inside your renderItem function:
Define just an array with the sources:
const [images, setimages] = useState([
require('./assets/image1.png'),
require('./assets/image2.png'),
require('./assets/image3.png'),
require('./assets/image4.png'),
require('./assets/image5.png')
]);
And use item and index for source and key:
return (
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
data={images}
renderItem={ ({ item, index }) => (
<Image source={item} /* Use item to set the image source */
key={index} /* Important to set a key for list items,
but it's wrong to use indexes as keys, see below */
style={{
width:260,
height:300,
borderWidth:2,
borderColor:'#d35647',
resizeMode:'contain',
margin:8
}}
/>
)}
/>
);

Related

Is there a FlatList-like View without the scrolling?

Basically, I have a list of items (with images) inside a single Card (custom component). Because the rendering of those items is slow, I wanted to use a FlatList to render them incrementally.
Unfortunately, I get the expected error
VirtualizedLists should never be nested inside plain ScrollViews ...
But I don't actually want to use a ScrollView inside the Card. I just want to render a few Items in a single Card, which should change its size to fit all the items.
Setting scrollEnabled={false} on the FlatList still shows the error above.
Using the ListHeaderComponent and ListFooterComponent props is not an option, because the content above and below should NOT be rendered inside the Card.
Here is a minimal example of what I mean:
const Comp = () => {
return (
<ScrollView contentInsetAdjustmentBehavior="automatic">
<Text>Header</Text>
<Card>
<FlatList
data={data}
renderItem={({ item }) => (
<Image source={{uri: item.localImageUrl}}/>
)}
keyExtractor={(item) => item.id}
scrollEnabled={false}
initialNumToRender={0}
maxToRenderPerBatch={3}
contentInsetAdjustmentBehavior='automatic'
/>
</Card>
<Text>Footer</Text>
</ScrollView>
);
};
What's interesting though, that aside from the error - I get the result I expected, and I could technically hide that error and ignore it, but that does not seem like the recommended approach.
Important: I am not specifically looking for a FlatList solution. It could technically be any Component that renders items incrementally in a non-blocking way.
The important point with a Flatlist is the reusing of cells so that not all components need to be rendered at the same time. So scrolling is an important part of this. On the other hand two scrollable components inside eachother will make it impossible for the system to know which component should be scrolled.
If there are only 3 items and it should not be scrollable you can just include a list of items inside the Scrollview like this:
const Comp = () => {
return (
<ScrollView contentInsetAdjustmentBehavior="automatic">
<Text>Header</Text>
<Card>
{ data.map((item, index) => {
return (
<Text key={index}>{item.title}</Text>
);
}) }
</Card>
<Text>Footer</Text>
</ScrollView>
);
};

React Native FlatList performance improvements

I'm reading barcodes and every barcode I read I add to an array and show in flatlist. but after 30 barcodes adding to the array getting slow. is there any solution I can do?
renderItem:
const renderItem = useCallback(
({item, index}) => (
<View style={styles.ListItemContainer}>
<Text>
-{item} index: {index}
</Text>
<TouchableOpacity
onPress={() => {
setRemovedItem(index);
setShowAlert(true);
}}>
<Text style={{fontSize: 20, fontWeight: 'bold'}}>X</Text>
</TouchableOpacity>
</View>
),
[],
);
FlatList component:
<FlatList
renderItem={renderItem}
data={barcodeArray}
style={styles.ListContainer}
keyboardShouldPersistTaps="handled"
initialNumToRender={12}
removeClippedSubviews
windowSize={12}
maxToRenderPerBatch={12}
/>
adding barcode:
const readBarcode = barcode => {
setbarcodeArray([barcode, ...barcodeArray]);
setbarcodeValue('');
setkey(key + 1);
};
for this solution you can use VirtualizedList instead Flatlist . In general, this should only really be used if you need more flexibility than FlatList .
for more info see this
Did you try using this: https://github.com/Flipkart/recyclerlistview library. It renders far fewer items than FlatList and then recycles them. Should be must faster and more performant than the native flatlist. If this does not work then try to use getItemLayout in flatlist if you have a fixed height of the content.

Flatlist Image source in React Native

I am trying to render a FlatList in React Native that it will be like an image carousel.
I want to provide the image sources in the assets folder and pass each items source in the renderItem but i get error undefined is not an object.
Here is the state:
export default function App() {
const [images, setimages] = useState([
{src:require('./assets/image1.png'),key:'1'},
{src:require('./assets/image2.png'),key:'2'},
{src:require('./assets/image3.png'),key:'3'},
{src:require('./assets/image4.png'),key:'4'},
{src:require('./assets/image5.png'),key:'5'}
]);
And here is the FlatList:
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
data={images}
renderItem={ ({images}) => (
<Image source={images.src} style={{
width:260,
height:300,
borderWidth:2,
borderColor:'#d35647',
resizeMode:'contain',
margin:8
}}></Image>
)}
/>
React Native FlatList renderItem callback get an object parameter with 3 props, item, index and separators:
renderItem
renderItem({item, index, separators});
You don't have to define keys in your array, just the images sources and then use item and index inside your renderItem function:
Define just an array with the sources:
const [images, setimages] = useState([
require('./assets/image1.png'),
require('./assets/image2.png'),
require('./assets/image3.png'),
require('./assets/image4.png'),
require('./assets/image5.png')
]);
And use item and index for source and key:
return (
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
data={images}
renderItem={ ({ item, index }) => (
<Image source={item} /* Use item to set the image source */
key={index} /* Important to set a key for list items,
but it's wrong to use indexes as keys, see below */
style={{
width:260,
height:300,
borderWidth:2,
borderColor:'#d35647',
resizeMode:'contain',
margin:8
}}
/>
)}
/>
);
UPDATE
We should never use indexes for JSX keys because on a rearrangement or the array, we'll end up with the same indexes pointing to different items.
There is an ESLint rule regarding that issue eslint-plugin-react:
eslint-plugin-react
Prevent usage of Array index in keys (react/no-array-index-key)
Warn if an element uses an Array index in its key.
The key is used by React to identify which items have changed, are added, or are removed and should be stable.
It's a bad idea to use the array index since it doesn't uniquely identify your elements. In cases where the array is sorted or an element is added to the beginning of the array, the index will be changed even though the element representing that index may be the same. This results in unnecessary renders.
We should create unique keys for each item (and maybe store them inside our images array if we have a large items count) by using some fast hashing algorithms like CRC32 on the image name or by using nanoid to generate a random key for each image.
This is happening because you're trying to destructure a images parameter which doesn't exist, it's called item.
Try this instead:
return (
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={images}
renderItem={({ item }) => (
<Image
source={item.src}
style={{
width:260,
height:300,
borderWidth:2,
borderColor:'#d35647',
resizeMode:'contain',
margin:8
}}
/>
)}
/>
);
the comment above is correct, however there is the uri attribute inside the source where you assign the url of the image see:
return (
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={images}
renderItem={({ item }) => (
<Image
source={{ uri: item.src }}
style={{
width:260,
height:300,
borderWidth:2,
borderColor:'#d35647',
resizeMode:'contain',
margin:8
}}
/>
)}
/>
);

React Native : uri rendered multiple times in flatlist

I'm a newbie to react native. I try to add a flatlist to my app.
I hava an array of datas designed like that:
["https://hi.com//image.png", //uri
"hello",
"https://hi.com//image2.png",
"welcome",
"https://hi.com//image3.png",
"great",
../..
]
Problem is that my image shows up but the text in the right side is actually my uri stringyfied.
I think there's something wrong with the keyExtractor:
renderItem =({item}) => {
return(
<View style ={{flex:1, flexDirection:'row'}}>
<Image source ={{uri: item}}/>
<View style ={{flex:1, justifyContent: 'center'}}>
<Text>{item}</Text>
</View>
</View>
)
}
render() {
return (
<View style={styles.mainContainer}>
<FlatList
data= {this.state.dataSource}
keyExtractor={(item,index) => index.toString()}
renderItem= {this.renderItem}
/>
</View>
);
}
your renderItem function loops thru every single element of array, not sure its the best option for your kind of data, maybe try to use something like this instead
const data = [{uri: 'https://link.io', text: 'hello'},{uri: 'http://anotherlink.co', text: 'bye'}]
then inside your renderItem fuction pass data:
<Image source ={{uri: item.uri}}/>
<Text>{item.text}</Text>
on the other hand if your you need to keep flat array, maybe be write some function with modulo of deviding index by 2 and from there get what goes where, but not sure why would you need that apart maybe from codewars challange ;)
good luck, hope this helps
your flatlist render item is trying to access the item in a loop.so everytime it gets looped,you are passing item to Image and item to Text.As #wijuwiju suggested,that is the best way to implement it.try to maintain keys to your data.Then your flatlist will render properly.
Store Item Like this:
profilePicture: 'https://picsum.photos/200',
Set Image Source Like this:
<Image source={{uri:profilePicture}}/>

React native flatlist initial scroll to bottom

I am trying to create a chat in React native using a <Flatlist />
Like WhatsApp and other chat apps, the messages start at the bottom.
After fetching the messages from my API, I call
this.myFlatList.scrollToEnd({animated: false});
But it scrolls somewhere in the middle and sometimes with fewer items to the bottom and sometimes it does nothing.
How can I scroll initially to the bottom?
My chat messages have different heights, so I can't calculate the height.
I had similar issue. If you want to have you chat messages start at the bottom, you could set "inverted" to true and display your messages and time tag in an opposite direction.
Check here for "inverted" property for FlatList. https://facebook.github.io/react-native/docs/flatlist#inverted
If you want to have you chat messages start at the top, which is what I am trying to achieve. I could not find a solution in FlatList, because as you said, the heights are different, I could not use getItemLayout which make "scrollToEnd" behave in a strange way.
I follow the approach that #My Mai mentioned, using ScrollView instead and do scrollToEnd({animated: false}) in a setTimeout function. Besides, I added a state to hide the content until scrollToEnd is done, so user would not be seeing any scrolling.
I solved this issue with inverted property and reverse function
https://facebook.github.io/react-native/docs/flatlist#inverted
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
<FlatList
inverted
data={[...data].reverse()}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
You can use this solution in chat component.
I faced the same issue with you and then I moved to use ScrollView.
It is fixed:
componentDidMount() {
setTimeout(() => {
this.scrollView.scrollToEnd();
});
}
<ScrollView ref={(ref) => { this.scrollView = ref; }} style={styles.messages}>
{
messages.map((item, i) => (
<Message
key={i}
direction={item.userType === 'banker' ? 'right' : 'left'}
text={item.message}
name={item.name}
time={item.createdAt}
/>
))
}
</ScrollView>`
Set initialScrollIndex to your data set's length - 1.
I.e.
<Flatlist
data={dataSet}
initialScrollIndex={dataSet.length - 1}
/>
There are two types of 'good' solutions as of 2021.
First one is with timeout, references and useEffect. Here's the full example using Functional Components and Typescript:
// Set the height of every item of the list, to improve perfomance and later use in the getItemLayout
const ITEM_HEIGHT = 100;
// Data that will be displayed in the FlatList
const [data, setData] = React.useState<DataType>();
// The variable that will hold the reference of the FlatList
const flatListRef = React.useRef<FlatList>(null);
// The effect that will always run whenever there's a change to the data
React.useLayoutEffect(() => {
const timeout = setTimeout(() => {
if (flatListRef.current && data && data.length > 0) {
flatListRef.current.scrollToEnd({ animated: true });
}
}, 1000);
return () => {
clearTimeout(timeout);
};
}, [data]);
// Your FlatList component that will receive ref, data and other properties as needed, you also have to use getItemLayout
<FlatList
data={data}
ref={flatListRef}
getItemLayout={(data, index) => {
return { length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index };
}}
{ ...otherProperties }
/>
With the example above you can have a fluid and animated scroll to bottom. Recommended for when you receive a new message and has to scroll to the bottom, for example.
Apart from this, the second and easier way is by implementing the initialScrollIndex property that will instantly loads the list at the bottom, like that chat apps you mentioned. It will work fine when opening the chat screen for the first time.
Like this:
// No need to use useEffect, timeout and references...
// Just use getItemLayout and initialScrollIndex.
// Set the height of every item of the list, to improve perfomance and later use in the getItemLayout
const ITEM_HEIGHT = 100;
<FlatList
data={data}
getItemLayout={(data, index) => {
return { length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index };
}}
{ ...otherProperties }
/>
I found a solution that worked for me 100%
Added the ref flatListRef to my flatlist:
<Flatlist
reference={(ref) => this.flatListRef = ref}
data={data}
keyExtractor={keyExtractor}
renderItem={renderItem}
/>
Then whenever you want to automatically scroll to bottom of the list use:
this.flatListRef._listRef._scrollRef.scrollToEnd({ animating: true });
yes you should access the element _listRef then _scrollRef then call the scrollToEnd 🙄
react-native 0.64.1
react 17.0.2
I've struggled on this as well and found the best possible solution for me that renders without a glitch is:
Use inverted={-1} props
Reverse the order of messages objects inside my array with data={MyArrayofMessages.reverse()} in my case data={this.state.messages.reverse()} using reverse() javascript function.
Stupidly easy and renders instantaneously !
Use inverted={1} and reverse your data by using the JS reverse function. It worked for me
<FlatList contentContainerStyle={{ flex: 1, justifyContent: 'flex-end' }} />
I am guessing that RN cannot guess your layout so it cannot know how much it needs to "move". According to the scroll methods in the docs you might need to implement a getItemLayout function, so RN can tell how much it needs to scroll.
https://facebook.github.io/react-native/docs/flatlist.html#scrolltoend
Guys if you want FlatList scroll to bottom at initial render. Just added inverted={-1} to your FlatList. I have struggle with scroll to bottom for couple of hours but it ends up with inverted={-1}. Don't need to think to much about measure the height of FlatList items dynamically using getItemLayout and initialScrollIndex or whats so ever.
I found a solution that worked for me 100%
let scrollRef = React.useRef(null)
and
<FlatList
ref={(it) => (scrollRef.current = it)}
onContentSizeChange={() =>
scrollRef.current?.scrollToEnd({animated: false})
}
data={data}/>
If you want to display the message inverted, set "inverted" to true in the flat list.
<Flatlist
data={messageData}
inverted={true}
horizontal={false}
/>
If you just want to scroll to the last message, you can use initialScrollIndex
<Flatlist
data={messageData}
initialScrollIndex={messageArray.length - 1}
horizontal={false}
/>
I spent couple of hours struggling with showing the first message on top without being able to calculate the item's height as it contains links and messages. But finally i've been able to...
What i've done is that i wrapped the FlatList in a View, set FlatList as inverted, made it to take all available space and then justified content. So now, conversations with few messages starts at top but when there are multiple messages, they will end on bottom. Something like this:
<View style={ConversationStyle.container}>
<FlatList
data={conversations}
initialNumToRender={10}
renderItem={({ item }) => (
<SmsConversationItem
item={item}
onDelete={onDelete}
/>
)}
keyExtractor={(item) => item.id}
getItemCount={getItemCount}
getItem={getItem}
contentContainerStyle={ConversationStyle.virtualizedListContainer}
inverted // This will make items in reversed order but will make all of them start from bottom
/>
</View>
And my style looks like this:
const ConversationStyle = StyleSheet.create({
container: {
flex: 1
},
virtualizedListContainer: {
flexGrow: 1,
justifyContent: 'flex-end'
}
};