skip to Main Content

How can i take an images into React-component?
My image is in srs/images.
I try to take it by:

useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axios.get("http://127.0.0.1:5000/api/user", {
                    headers: {
                        Authorization: `Bearer ${localStorage.getItem("access_token")}`,
                    },
                });

                const {firstName, lastName, avatar} = response.data;
                setFirstName(firstName);
                setLastName(lastName);
                setAvatar(avatar);
            } catch (error) {
                console.error("Error fetching user data:", error);
            }
        };

        fetchData();
    }, []);

my avatar looks like ../images/first_image.png and than i can’t view it in

<img src={avatar}
    alt={"Avatar"}
    style={{marginLeft: "5%", width: "4vh"}}/>

in my postgres sql the image is like the path:
../images/four_image.png

2

Answers


  1. If the image file is in src/images I think the url needs to be images/first_image.png (you need to ditch the ‘..’ at the beginning. If all avatar images are stored in this folder, it might be best to store just the filename in the database and have the img src be the filename + a baseUrl:

    <img src={baseUrl + avatarFilename}
        alt={"Avatar"}
        style={{marginLeft: "5%", width: "4vh"}}/>
    

    where

    const baseUrl = 'images/'
    
    Login or Signup to reply.
  2. <img src={require(avatar)}
    alt={"Avatar"}
    style={{marginLeft: "5%", width: "4vh"}}/>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search