How to give Image src dynamically in react js?

前端 未结 4 1574
后悔当初
后悔当初 2020-12-10 11:25

I am trying to give image name in src dynamically. I want to set image name dynamically using variable with path. but I am not able to set src correctly. I tried solutions o

相关标签:
4条回答
  • 2020-12-10 11:38

    You can still use require

    <img src={require(`./img/${img.code}.jpg`)}/>
    

    It's not recommended to manually add images to the public folder. See this answer here: https://stackoverflow.com/a/44158919/1275105

    0 讨论(0)
  • 2020-12-10 11:50

    if you dont want to require the image then you have to put all your images into public folder and then

    <img src={`../img/${img.code}.jpg`}></img>
    

    this method will work.

    0 讨论(0)
  • 2020-12-10 11:54

    If you guys get the path from the database for multiple images and need to use in single tag, you can follow the below method. step 1 : Please make sure the images are in public folder. step 2 : Update your path should start from public not from src. step 3 : Make sure to verify that the path should be using like a variable. If your images path should be using in variable imgPath. You can use your code like var imgPath = '/img/pic.jpeg' "src={imgPath}"

    I hope this will help you..

    0 讨论(0)
  • 2020-12-10 11:57

    Dynamic require doesn't seems to be clean and also eslint isn't happy with it (not sure why)

    Other two approaches if images are stored in public folder :

    const imgNameWithPath = '/fullImageNameWithPath.jpg'

    1. Using env <img src={process.env.PUBLIC_URL + imgNameWithPath} />

    2. Using location origin: <img src={window.location.origin + imgNameWithPath} />

    0 讨论(0)
提交回复
热议问题