Dmitriy Kovalenko Dmitriy Kovalenko - 4 years ago 152
React JSX Question

Import random file, using react js, babel and es6

I have an issue with displaying of random image with webpack. I have a directory, with several images, like

1.jpg, 1-cropped.jpg
2.jpg, 2-cropped.jpg


And I need to fetch random image from there. It would be better If I will not be needed to mannually add a reference for each file. But if there - I whatever do not understand, how can I reference to imported variable, like

import 1 from '../1.jpg'


If I only know the generated number of it. Thanks a lot.

Answer Source

It's easy. You can use require inside the render. Like the example below:

render() {
    const {
      someProp,
    } = this.props

    const graphImage = require('./graph-' + anyVariable + '.png')
    const tableImage = require('./table-' + anyVariable2 + '.png')

    return ()
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download