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.

1
  • Might be worth looking into this technique if you want to have dynamic imports. Commented Mar 15, 2019 at 12:15

1 Answer 1

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} ... />
Sign up to request clarification or add additional context in comments.

4 Comments

why not just const { icon } = require('../assets/myPng.png'); ?
Because require(...) usually returns a string when used on a picture, not an object. You will get undefined here.
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.
Well, import can be used dynamically, see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.