skip to Main Content

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


  1. Chosen as BEST ANSWER

    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
    

  2. 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')}
        ...
        ...
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search