-1

hello i try to 'import image from ../img/number_of_my_user_id.png' how to do this please ?

my code is :

import React, { useState, useEffect } from 'react'
//i want to something like this
import Image from `../image/${userid}.png`

const [userid, setUserid] = useState(null);

const userConnected = useEffect(() => {
    (async () => {
        try {
            const resp = await 
            httpClient.get("//localhost:5000/@me");
            setUserid(resp.data.id);
        } catch (error) {
            console.log("Not authenticated");
        }
    })();
}, []);

please i really need help, my question is, how can i import an image whose name deppending to user Logged in ?

i don't know how can i import my user Image....

  • There are some helpful suggestions here https://stackoverflow.com/questions/53775936/import-image-dynamically-in-react-component – msmoore Sep 02 '22 at 10:11
  • Is that your whole code? I mean because there is no component there – S.Marx Sep 02 '22 at 10:19
  • Is the list of your user ids static or dynamic? I mean, for example, do you have a list of users from id 1 to id 20, or you may have a variable number of users, like in most applications? – Emanuele Scarabattoli Sep 02 '22 at 10:52

2 Answers2

1

you can do this

const [image, setImage] = useState(null);
  const loadImage = (userid) => {
    import(`../image/${userid}.png`).then(image => {
      setImage(image);
    });
  };
0

As far as I can see, this can be easily done by using a template string like this:

const imageUrl = `/img/${userid}.png`

And now you could render an image with this path as the source:

<img src={imageUrl} />

The only thing left doing is to transfer the images to a folder with is accessable via web. If these images should not be public you must implement some security details as well.

Back to your question: I can not imagine a usecase where you would import an image with an import statement in javascript code. That is against basic best practises.

m4lt3
  • 465
  • 2
  • 15