0

I have a react native project. I currently have a list I want to render dynamically based on an array of objects that I have. One of the key values in the array is image:'name.png'. I am passing in the object in to a flatlist. Each element in the array has a different image file name.

Inside of each element I want to render the image and for the image item, I am try8ing to currently use the require key word with a string that will render the images but it is currently not rendering I am not sure why. What should I do.

flatlist:

 const homeTypeOptions1 = [ { key: 1, value: 'Houses', image: 'home.png' }, { key: 2, value: 'Condos', image: 'building.png' }, { key: 3, value: 'Lot/Land', image: 'management.png' }, { key: 4, value: 'Multi-family', image: 'multi-family.png' }, { key: 5, value: 'Manufactured', image: 'tiny-house.png' }, { key: 6, value: 'Townhomes', image: 'townhouse.png' } ] <View style={styles.sectionContainer}> <FlatList style={styles.homeTypeContainer} data={homeTypeOptions1} keyExtractor={(item) => {item.key}} numColumns={numberOfColumns} renderItem={(item) => {return(<GridItemComponent item={item}/>)}} /> </View> 

itemComponent:

import React, { useState } from 'react' import { View, Text, TouchableOpacity, StyleSheet, Image } from 'react-native' const GridItemComponent = ({item}) => { const imageUrl = '../../assets/' + item.item.image return ( <View style={styles.itemContainer}> <Image source={require('../../assets/' + item.item.image)}/> <Text>{item.item.value}</Text> </View> ) } const styles = StyleSheet.create({ itemContainer: { width: '33%', } }) export default GridItemComponent 

Here is the folder structure:

folder structure

0

1 Answer 1

1

It should be item.image and item.value

 const GridItemComponent = ({item}) => { const imageUrl = '../../assets/' + item.image; return ( <View style={styles.itemContainer}> <Image source={require(imageUrl)}/> <Text>{item.value}</Text> </View> ) } 

and the keyExtractor should be

keyExtractor={(item) => item.key} 

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#description

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.