How to load an image onto the page with react from dynamic data?

非 Y 不嫁゛ 提交于 2019-12-11 08:36:54

问题


I want to display an image on my react app page

import egypt from '../images/egypt.svg'

<div>
   <img src={egypt}/>
</div>

Is this the correct way to do this?

Also I want to load it in from an object like this:

options: [{
       optionOne: {
         answer: 'bolivia',
         image: './images/egypt.svg'
       }
     }]

how can I display it on screen?

my error is saying I need an appropriate loader. I tried to use this: https://www.npmjs.com/package/image-webpack-loader

but it says: Can't resolve 'file-loader'

  {
    test: /\.svg$/i,
    loaders: [
        'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
        'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]
  }

回答1:


If

import egypt from '../images/egypt.svg'

<div>
   <img src={egypt}/>
</div>

works in your code and you have configured the webpack properly, you would be able to dynamically display the image in React by requiring them with the help of template literals like

<img src={require(`${obj.optionOne.img}`)}

Also make sure you install url loader with command

npm install -s url-loader

You need to configure your webpack with url-loader as

 {
        test: /\.(jpe?g|png|gif|svg)$/,
        use:['url-loader']
    }


来源:https://stackoverflow.com/questions/45287748/how-to-load-an-image-onto-the-page-with-react-from-dynamic-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!