1

I am uploading less code because I think it is enoug
Ask if need more to find error

async componentDidMount(){


var image = this.props.data.img
console.log(this.props.data.img == './../images/thumbnails/g.png') // true
console.log(this.props.data.img === './../images/thumbnails/g.png') // true
console.log(typeof(this.props.data.img))
await import(image)
            .then((res)=>{
                console.log(res)
                this.setState({img:res})
            })
            .catch((e)=>{
                console.log(this.props.data.img)
                console.log(e)
            })
}

I am trying to import image.
When i use import('./../images/thumbnails/g.png) then it run successfully but when i pass same value as props and tries to import that then it through error (module not found).
I log the values and all are coming out to be true that mean string and string by props are same then why i am getting 2 different behavior?

Siavash
  • 2,813
  • 4
  • 29
  • 42
Rajan Lagah
  • 2,373
  • 1
  • 24
  • 40
  • You can't import the file by passing string as variable to `import`. Check https://stackoverflow.com/a/47956054/7232300 – Prakash Sharma Oct 20 '18 at 11:11
  • 1
    Basically when your module bundler is bundling your application at that time value of `this.props.data.img` is not available because that value is only available during runtime (i.e. after bundling). – Prakash Sharma Oct 20 '18 at 11:17

1 Answers1

0

You should install the file-loader on your application, then use the image in your jsx/js/css files.

to install file-loader use below command:

npm install file-loader --save-dev

And update your webpack by following code:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}
          }
        ]
      }
    ]
  }
}

Then import your file

import img from './file.png'

For loading Images based on props you can do these ways:

<img src={require(this.props.name)} alt=''/>

or

<img src={require('../assets/images/yourimage.png')} alt=''/>

or

<img src={require(`../assets/images/${this.props.name.toLowerCase()}.png`)}/>
Siavash
  • 2,813
  • 4
  • 29
  • 42
  • 1
    I am successfully loading images on site but not able to do same when pass image path string value as props. I have set file-loader and it is working fine – Rajan Lagah Oct 20 '18 at 11:10
  • 1
    I need to use `` but it is throwing error **Uncaught Error: Cannot find module "."** and this is actually a different string – Rajan Lagah Oct 20 '18 at 11:29