0

I try to dynamically display a list of local images, which are stored in the folder .img/. React Native throws the error „Unknown named module: ‚./img/a1.jpg‘ with my implementation. I read about the problem of dynamically requiring images, but wasn’t able to solve the problem. Do you have any suggestions?

export class ImageList extends React.Component { constructor() { super(); } render() { const datav2 = [ "./img/a1.jpg", "./img/a6.jpg" ]; const lapsList = datav2.map((data) => { var testPath = require(data); return ( <View> <Image source={testPath} style={{width: 50, height: 50, backgroundColor: "#33ff00"}} /> </View> ) }) return ( <View> {lapsList} </View> ); } } 

2 Answers 2

2

You can remove the dynamic loading by adding require directly inside your array.

render() { const datav2 = [ require("./img/a1.jpg"), require("./img/a6.jpg"), ]; const lapsList = datav2.map((data) => { return ( <View> <Image source={data} style={{width: 50, height: 50, backgroundColor: "#33ff00"}} /> </View> ) }) return ( <View> {lapsList} </View> ); } 

In addition, you should move datav2 outside the render() method to not require images on each render.

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

Comments

1

Yes you should add require in the array and then put the datav2 variable outside render() , don't forget to add the index in the array map to be key in the view return so there is no warning in your apps, like this :

const datav2 = [ require("./img/a1.jpg"), require("./img/a6.jpg"), ]; export class ImageList extends React.Component { constructor() { super(); } render() { const lapsList = datav2.map((data,i) => { return ( <View key={i}> <Image source={testPath} style={{width: 50, height: 50, backgroundColor: "#33ff00"}} /> </View> ) }) return ( <View> {lapsList} </View> ); } } 

And this is the result example when i try it on my emulator :

enter image description here

I hope this answer can help you :)

1 Comment

Index as key is an anti-pattern.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.