Reputation: 137
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>
);
}
}
Upvotes: 0
Views: 308
Reputation: 679
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 :
I hope this answer can help you :)
Upvotes: 1
Reputation: 1118
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.
Upvotes: 2