0

i have a react component and i want to import an image inside of it. The image is in the same folder as the component So i enter <img src={require('./hi.png')} />. But the console shows an error:

Uncaught Error: Cannot find module "./hi.png"
    at webpackMissingModule (bundle.js:46105)
    at MainNavigationBar.render (bundle.js:46105)
    at bundle.js:15841
    at measureLifeCyclePerf (bundle.js:15120)
    at ...

Why is that? What im doing wrong?

2
  • if the image exist in the same folder then u can use it like this: <img src='hi.png' /> try it. Commented Jan 31, 2017 at 9:51
  • it didi show a error but the images did not appear Commented Jan 31, 2017 at 10:04

3 Answers 3

1

I also tried to use

<img src={require('./hi.png')} />

It is showing require is unresolved function or module and throws the same error as not able to find hi.png

But you can use it as following way to resolve the issue

import hi  from "./hi.jpg";
<img src={hi} />
Sign up to request clarification or add additional context in comments.

Comments

1

I will suposse that you folder project tree is similar that and your server side was made with Nodejs, cause it was not clear in your question:

.projectFolder
|--.client
|   |--.components
|   |--bundle.js
|   |--index.js
|   |routes.js
|
|--.node modules
|--.server
    |--.public
    |   |--.assets
    |       |--.images
    |       |  |--hi.png
    |       |
    |       |--.css
    |
    |--index.html
    |--index.js

Therefore I advise you to use a Static folder and call this using:

app.use(express.static(path.join(__dirname, 'public')));.

So, everything inside public will be tracked and you can just callback these image with:

<img src={'/assets/images/hi.png'} width="150px" className="lateral-margin" />

Not having the necessity of use require, or anything like that. Sure, of this way your code keep more organized to other and for you too.

However, in your case require is not working because probably you neither setting your webpack nor npm installed babel-loader. Read more about loaders, download and set it with:

module: {
  loaders: [
    {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      loader: 'babel-loader',
      query: {
        presets: ['es2015']
      }
    }
  ]
}

Comments

0

try to import and call your image differently :

import hi from '/assets/images/hi.png'; 



    <div style={{ backgroud :`url(${hi})`}}>
    </div>

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.