Home > Net >  Image paths are not resolved within component that gets parameters from the url
Image paths are not resolved within component that gets parameters from the url

Time:03-14

I have a component that gets parameters via the url, and uses useParams(). In this component I want to display an image, but the image is not displayed. When I disable the ability to send url parameters to this component, the image is displayed. The image is in the public folder.

Without sending params:

//App.js
          <BrowserRouter>
            <Routes>
              <Route path='/somePath' element={ <SomeComponent/>}/>
            </Routes>
          </BrowserRouter>


//SomeComponent.js
    export default function SomeComponent() {
      return (
        <img src='butterfly.png'/>
      )
    }

With parameters:

//App.js     
          <BrowserRouter>
            <Routes>
              <Route path='/somePath/:someParameter' element={ <SomeComponent/>}/>
            </Routes>
          </BrowserRouter>


//SomeComponent.js
    export default function SomeComponent() {
        const { someParameter } = useParams();
      return (
        <img src='butterfly.png'/>
      )
    }

Sandbox example https://codesandbox.io/s/nostalgic-colden-16rfb0?file=/src/App.js

CodePudding user response:

it should

<img src='/butterfly.png'/>

if you don't add "/" your image URI will be : /somePath/:someParameter/butterfly.png', this is wrong

  • Related