List of images using React Native's FlatList

Seeking assistance with integrating images into a flatlist grid. I have successfully implemented text but struggling with images stored in the assets folder.

The goal is to display separate images from the assets folder within the boxes of the flatlist grid.

If more details are needed, please let me know!

Below is the code snippet:


import React from 'react';
import { View, Image, Text, StyleSheet, TouchableOpacity, FlatList, Dimensions } from 'react-native';
import { drawer } from '../navigation/AppNavigation';
import { hp, wp } from '../utils/responsiveScreen';

const dataList = [{ key: '1' }, { key: '2' }, { key: '3' }, { key: '4' }, { key: '5' },{ key: '6' },{ key: '6' },{ key: '6' }];

const numColumns = 2;
const WIDTH = Dimensions.get('window').width;

const Main = () => {

formatData = (data, numColumns) => {
const totalRows = Math.floor(data.length / numColumns);
let totalLastRow = dataList.length - (totalRows * numColumns);

while(totalLastRow !== 0 && totalLastRow !== numColumns){
dataList.push({'key': 'blank', empty: true});
totalLastRow++;
}
return dataList;
};

_renderItem = ({ item, index }) => {
let {itemStyle, itemText} = styles;

if(item.empty){
return <View style={[itemStyle]}/>;
}

return (
<View style={itemStyle}>
<Text style={styles.itemText}>{item.key}</Text>
</View>
);
};

return (
<View style={styles.container}>
<TouchableOpacity
style={{ height: 50 }}
onPress={() => drawer.current.open()}>
<Image source={require('../assets/menu.png')} />
</TouchableOpacity>
<Text style={styles.textStyle}>Stars</Text>

<FlatList
data={this.formatData(dataList, numColumns)}
renderItem={this._renderItem}
keyExtractor={(item, index) => index.toString()}
numColumns={numColumns}
/>

</View>
);
};

And here is the Style sheet:


const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
paddingTop: hp(7),
paddingHorizontal: wp(6),
},
textStyle: {
marginBottom: 20,
fontWeight: 'bold',
fontSize: 24,
color: 'black',
},
image: {
alignSelf: 'center',
height: hp(40),
width: hp(40),
marginTop: hp(3),
},
itemStyle: {
backgroundColor: 'pink',
alignItems: 'center',
justifyContent: 'center',
height: 150,
flex: 1,
margin:1,
width: WIDTH / numColumns
},
itemText: {
fontSize: 50
}
});

Showing a preview of the current layout: Here

UPDATE

Updated the datalist as follows:


const dataList = [{ key: '1', image: require('../assets/backGround.png')}, { key: '2', image: require('../assets/backGround.png') }, { key: '3', image: require('../assets/backGround.png')}];

Adjusted the view like this:

 
<View style={itemStyle}>
{/* <Text style={styles.itemText}>{item.key}</Text> */}
<Image
style={styles.image}
source={item.image}
/>
</View>

Encountering an error now:

TypeError: 'required' is not a function. The issue occurs when trying to fetch the image ('require('../assets/backGround.png')'), where 'require' seems to be undefined.

Answer №1

const infoList = [{ id: '1',img: require('../assets/backPic.png')}, { id: '2', img: require('../assets/backPic.png') }, { id: '3' ,img: require('../assets/backPic.png')}]

should look like this

const infoList = [{ id: '1',img: require('../assets/backPic.png')}, { id: '2', img: require('../assets/backPic.png') }, { id: '3' ,img: require('../assets/backPic.png')}]

Answer №2

To display the image, make sure to include a require() statement in the source attribute of the image tag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating Apache Arrow vectors in TypeScript for writing data to a Table

Currently, I am in the process of creating a method that is designed to take a column of data, referred to as data: any[], and then pack it into an Arrow-typed Array Buffer for insertion into an Arrow table. To illustrate with an example, if we consider T ...

Navigating to a different intent within the DialogFlow Messenger fulfillment can be done by utilizing the 'agent.setFollowupEvent(targetIntentEventName)' method

I am currently exploring ways to initiate another DialogFlow Intent (using its event) from a webhook server built with node.js. This will occur after gathering the user's email address, verifying their registration status by sending a POST API request ...

JavaScript array loading failed for the C# web service

I am encountering an issue with a JavaScript object in my application that contains an array object, which is a collection of objects with two properties (Name, Value) on the server-side. Despite my efforts, when the code reaches the C# web service, the C ...

Sending a form cancellation submission within a nested function call

I need help preventing my form from submitting in case the confirmation message is cancelled. How can I achieve this within the each() loop? $('#myForm').submit(function() { var inputs = $(this).find('input:checked'); inputs.ea ...

gmap3 has encountered an error: undefined is not a valid function

I am working on a WordPress site and trying to integrate a Google map into the contact page. However, I'm encountering an error Uncaught TypeError: undefined is not a function in the JavaScript console. Below is the code snippet causing the issue, can ...

Error message: jQuery AJAX request fails due to permission denial issue on Internet Explorer

I am facing a major challenge on my website. I have implemented AJAX to update the content of a DIV, which works perfectly on all pages except for some links under the Portfolio tab. The links for "photography", "interactive", "print", and "traditional" tr ...

Limiting jQuery searches to a specific region: Tips and tricks

If I have the code snippet below: <div class="foo"> <div> some text <div class="bar"> </div> </div> </div> <div class="foo"> <div> some text <div class="bar"> some text </div> </div> </ ...

The pagination feature in React MUI DataGrid is malfunctioning

I am currently working with a datagrid and implementing server-side pagination. I have set a limit of 5 objects to be returned from the backend, and an offset variable to indicate from which index the next set of data should come. const handlePageChange = ...

Strange issue encountered when utilizing Worklight along with XSL transformation on a JSON response

I'm facing an unusual issue that I can't seem to resolve. Here is an example of a JSON response that I am dealing with. "values": [ { "time": "2014-02-26T09:01:00+01:00", "data": [ "A", "B" ] }, // additional objec ...

Creating a unique, random output while maintaining a log of previous results

While working on a recent project, I found myself in need of a custom Javascript function that could generate random numbers within a specified range without any repetitions until all possibilities were exhausted. Since such a function didn't already ...

Similar to Angular ui-router 1.0.3, what is the equivalent function for reloadOn

After updating to UI-router v1.0.3 from v0.3.2, I noticed that the reloadOnSearch feature has been removed from the stateConfig. I'm having trouble finding the equivalent of reloadOnSearch in v1.0.3. It doesn't seem to be documented anywhere. A ...

What exactly does the 'app://' scheme entail when it comes to assets within Webpack-5-generated applications during development mode?

I've recently noticed a unique behavior in my Webpack 5-built application during development mode. The browser requests assets using a URL with an interesting app:// scheme. An example of this is: app:///node_modules/dir/to/package/index.js In the De ...

Every time I try to access Heroku, I encounter an issue with Strapi and the H10 error code

Upon opening Heroku and running the command "heroku logs --tail", my app encountered a crash and I can't seem to locate my Strapi application in Heroku. 2020-05-04T19:05:38.602418+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GE ...

The hamburger icon seems to be frozen and unresponsive

I'm struggling to get my hamburger icon to reveal the navigation bar when clicked. The icon itself functions properly and adapts to different screen sizes, but the overlay remains stationary. Check out my code on JSFiddle! <html> <head> ...

Checking to see if there are a minimum of two checkboxes selected before inputting the data into the database

I am currently using a combination of HTML, PHP, JavaScript, MySQL, and Wampserver. In my project, I have implemented 3 checkboxes where the user can choose a maximum of two options. Once selected, these choices are then inserted into the database. Initi ...

Having the same name for multiple query parameters does not result in an array being returned

Using the link http://example.com/users?test=1&test=2 router.route('/users/?').get((req, res) => { console.dir(req.query) //=> { test : 1 } }) The output is { test : 1 } instead of an expected array [ 1, 2 ]. Even ?test[]=1&test ...

Following the upgrade to version 6.3.3, an error appeared in the pipe() function stating TS2557: Expected 0 or more arguments, but received 1 or more

I need some assistance with rxjs 6.3.3 as I am encountering TS2557: Expected at least 0 arguments, but got 1 or more. let currentPath; const pipeArgs = path .map((subPath: string, index: number) => [ flatMap((href: string) => { con ...

Why are the values in my options created using the array map method empty in React?

I decided to use a for loop to generate an array containing the numbers 1 through 12 representing each month. I then attempted to utilize the map array method to create 12 options, but unfortunately they are coming up empty. Below is a snippet of the ...

Dev4: utilizing scaleOrdinal for color mapping and selection

I have developed a code that generates line graphs on an SVG canvas, however, I am facing difficulties in altering the colors as I defined using the d3.scaleOrdinal function. Despite defining 12 distinct colors, the output I am getting looks like this. Is ...

JQuery function fails to execute upon first page load

I am currently facing a situation where I need to wait for a specific image to load before either swapping out its src or showing/hiding the next image. The desired outcome is to display a placeholder image (silhouette) until the main image loads, then hi ...