How Can I use Laravel's server link in react

I'm a newbie to react. So this question could be childish, so pardon me for my mistakes.

There are some components where I need to show images from public/images directory and some images from public/images/products.

I've written in web.php

Route::get('/{path?}/{path2?}/{path3?}'), function(){
    return view('app');
});

first path? is all the pages general users can see, so all images are being shown correctly. If the request URL is http://127.0.0.1:8800/home then images showing correctly. Here images links are like http://127.0.0.1:8800/images/product.jpg

enter image description here

If the request URL is http://127.0.0.1:8000/manage/products/view_products then images are not loaded. Here images links are like http://127.0.0.1:8800/manage/products/images/product.jpg

enter image description here

So how will I be able to get server url to get proper images from public/images folder? Or expecting better approaces.

Upvotes: 0

Views: 395

Answers (1)

Sudhanshu Kumar
Sudhanshu Kumar

Reputation: 2044

This does not work because the URLs of the images are relative to the browser's URL, A better approach would be to declare a constant in the .env file of your project which would point to the "images" asset directory, and prefix your image URL with that constant. I've added a very little example.

<img src={`${base_path}/${src}`} />

This way your image source will not depend on the current route.

Upvotes: 1

Related Questions