Search code examples
javascriptreactjsurlreact-routerreact-router-dom

React , "product/:id" page causes components assets to load from incorrect path(wrong path)


im creating a Product linding page (single product page) with react but when loading the navbar component

it couses the componint's assists to load from wrong path for examble product page path is (/product/:id) the navbar component will go (/product/:id/assist name ) to get the assist witch will not load the assist because that is not the right path for the asities. the exists on the (./assist name )

app.js file

function App() {
  return (
    <Router>
      <Container>
        <Routes>
          <Route path="/"  element={<Home />} />     
          <Route path="/products/:id" element= {<SingleProductPage/>} />
        </Routes>
      </Container>
    </Router>
  );
}

single product page that has's the (/product/:id) path

function SingleProductPage() {

 
  
  return (
    

    <div id="single-Container">
      
      <Navbar/>
     
      single page

    </div>
    



    )
}

the navbar component

 <div id="Navbar-SearchIcon" >
    <img src="../searchIcon.png" alt="" />


<div id="Navbar-BasketButton" >
       <img src="./basket-icon.png" alt="" />
          </div>

when im on (/) path or any other path

when im on (/product/:id) path

how the navbar should look like

how the navbar look like on product/:id page


Solution

  • The image sources are using relative paths instead of absolute paths in the PUBLIC directory. When you navigate into a sub-route the path to assets will be different when using relative paths, they will be relative from the current URL pathname.

    Absolute paths will start with "/" which is the public directory. Here's an Example:

    <div id="Navbar-SearchIcon" >
      <img src="/images/searchIcon.png" alt="" />
    </div>
    
    <div id="Navbar-BasketButton" >
      <img src="/images/basket-icon.png" alt="" />
    </div>
    
    /public
      -/images
        -searchIcon.png
        -basket-icon.png
        ....
      ....
    /src
      ....