vite react dynamic image url

Viewed 1818

hello guys i have problem with vite react dynamic images url not loading correctly and thats my component

 <Flex>
      {data?.map((tag) => (
        <Box key={tag._id}>
          <Image w="150px" h="150px" src={`http:localhost:5000/${tag.imageUrl}`}></Image>
        </Box>
      ))}
    </Flex>

when i check the network tab i see that the url of the client is added to the image url

http://localhost:3000/localhost:5000/uploads/1623642756947--Capture.PNG

in create react app maybe we can use reqiure() to fix that but i dont know how to fix that in vite and adding reqiure() throw an error

1 Answers

when i check the network tab i see that the url of the client is added to the image url http://localhost:3000/localhost:5000/uploads/1623642756947--Capture.PNG

This is because importing a static asset in vite return the resolved public URL when it is served.

This excerpt from the offical doc say (adapted according your question):

  • For example, http//:localhost:5000/${tag.imageUrl} will be /http:localhost:5000/uploads/1623642756947--Capture.PNG during development,

  • and become /assets/http:localhost:5000/uploads/1623642756947--Capture.PNG in the production build.

The solution is to use the server.proxy option of vite config to forward your dynamic assets requests to the desired server, in vite.config.js add:

  server: {
    proxy: {
      // forward `/uploads/` endpoint to -> `http://localhost:5000/uploads/`
      '^/uploads': {
        target: 'http://localhost:5000/'
      }
    }
  }

So in your component, Image should be declared like that :

<Image w="150px" h="150px" src={`${tag.imageUrl}`}></Image>

Now when you hit http://localhost:3000/uploads/1623642756947--Capture.PNG

The asset (image) will be loaded from to http://localhost:5000/uploads/1623642756947--Capture.PNG

You can get more information about Static Assets Handling here and vite proxy options here.

Solution tested and working ✔

Related