I want to display image randomly in React. Images are placed inside src/assets folder.
I have to display them using props.
Row.js:
import React from 'react'
import {View, Text } from 'react-native';
const Row = (props) => (
<View style={{flex:1, flexDirection: 'row'}}>
<img src={require(props.value)}> //Error: Cannot find module '../assets/icondelivery.PNG'
</img>
<Text>{props.value}</Text>
</View>
)
export default Row
props.value contains : ../assets/icondelivery.PNG
Hierarchy is : src/assets/icondelivery.PNG
Note: If I pass <img src={require('../assets/icondelivery.PNG')}> , it works.
CodePudding user response:
Put assets folder in public folder. Change path from ../assets/icondelivery.PNG to ./assets/icondelivery.PNG Use this code:
import React from 'react'
import {View, Text } from 'react-native';
const Row = (props) => (
<View style={{flex:1, flexDirection: 'row'}}>
<img src={process.env.PUBLIC_URL props.value}/>
<Text>{props.value }</Text>
</View>
)
export default Row
CodePudding user response:
For dynamic image sources that are known then you can use require()
in your definitions instead of within the img src itself.
For example
<Row value={require('../assets/icondelivery.PNG')} />
Then in the component:
<img src={props.value}>
If you have a structure containing the images like an array you could put require()
there:
const images = [
{ name: 'delivery', src: requiure('../assets/icondelivery.PNG')}
...
...
]