skip to Main Content

I write the code below,

 source={require(`../../assets/images/${post.image}`)}

in this {post.image} have dynamic values, its something like an array – img1.png,img2.png likewise

How to concatenate this path and values.
It’s working on react but it’s not working on react-native, How to solve that issue ?

2

Answers


  1. In react native you can’t have dynamic resources with require. Check React Native docs for solution:

    https://reactnative.dev/docs/images#static-image-resources

    you can’t use variable in require. You can store your resource in an constant like

    const img1 = '../../assets/images/img1.png'
    
    <Image source={require(img1)} />
    

    Or string constant directly

    <Image source={require('../../assets/images/img1.png')} />
    
    Login or Signup to reply.
  2. documentation link was provided in the answer by @role

    in the documentation for images in assets folder

      assets
         -app_icon.png 
    

    use the asset:/ scheme

     <Image
      source={{ uri: 'asset:/app_icon.png' }}
      style={{ width: 40, height: 40 }}  // Also you have to specify image dimensions manually
     />
    

    if that does not work then create a dictionary of image components

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search