0

I'm using react-google-maps but I think my question applies a general user case. I want to dynamically load an icon, using a url passed in as a prop. But I find if I use a variable I get an error. Please see below:

When I require and icon using a string it works fine e.g.

icon={require('../assets/myPng.png')}

But if my png path is a variable for example

let url = '../assets/myPng.png'

icon={require(`${url)`}

I get error:

cannot find module '../assets/myPng.png'

Can anyone tell me what is going on ?

if I use icon={require(url}, that fails also.

vahdet
  • 6,357
  • 9
  • 51
  • 106
dorriz
  • 1,927
  • 3
  • 12
  • 19
  • Might be worth looking into [this technique](https://stackoverflow.com/questions/47954655/dynamic-imports-in-es6-with-runtime-variables) if you want to have dynamic imports. – Tholle Mar 15 '19 at 12:15

1 Answers1

2

It's better to use require(...), so the path will be managed by your package manager. If you use directly a string, it will bypass it, and you will get the error. I would advise to use:

const icon = require('../assets/myPng.png')
// ...
<MapComponent icon={icon} ... />
soywod
  • 4,377
  • 3
  • 26
  • 47
  • why not just `const { icon } = require('../assets/myPng.png');` ? – Scriptkiddy1337 Mar 15 '19 at 11:53
  • 1
    Because `require(...)` usually returns a string when used on a picture, not an object. You will get `undefined` here. – soywod Mar 15 '19 at 11:53
  • Thanks for your comments , but I need to have the require(...) use a variable and to dynamically load the icon depending on the user, I cannot use hardcode a string . I see npm dynamic-import and will try that , but from more investigation it seems impossible to dynamically require something in the way I want - unfortunately I cannot use import. – dorriz Mar 15 '19 at 12:15
  • Well, import can be used dynamically, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports – soywod Mar 15 '19 at 12:19