0

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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')}
    ...
    ...
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.