React can't load jpg image when redirected to home page when loaded

Viewed 273

I have a react app that redirects the user to the home page on start. If I use <Redirect to="/Home"> I am taken to the page, but my image is not loaded and I am met with a 404 error. However, if I don't use redirect and just load the component at the start in my render function, the image appears just fine and there are no issues with pathing. Something odd occurs when using Redirect and I am not sure if I am using the correct approach for setting up a default page for when the app starts.

The image is within my src folder under src/media/profile.jpg. Whether I add a "./" in front of the path or remove the forward slash, the results are the same. I've done import statements for the image and even tried src={require('../media/profile.jpg')} in the image tag. The issue is only when I redirect.

With Redirect

enter image description here

Render Function from App class

`

  <Router>
  <Redirect from="/" to="/Home" />
  
  <Switch>
    <Route exact path="/Home">
        <Home />
    </Route>
    <Route exact path="/ReactDefault">
        <ReactDefault />
    </Route>
  </Switch>
  </Router>
    
    
  </main>

Import in homepage

import Avatar from '../media/profile.jpg'

//var Avatar = require('../media/profile.jpg')

Home Page

`

  <Router>
  <img  src={Avatar}  id="avatar" alt="avatar"></img>
  <div id="cardup-wrap">
    <card-up><Link id="test" to="/ReactDefault" ><h2 >Test1</h2></Link></card-up>
    <card-up><Link id="test" to="/ReactDefault" ><h2>Test1</h2></Link></card-up>
    <card-up><Link id="test" to="/ReactDefault" ><h2>Test1</h2></Link></card-up>
  </div>

  </Router>

</div>`

` {

Webpack Config

test: /\.(png|jpe?g|gif)$/i,

    use: [

      {
        loader: 'file-loader',

      },
    ],
  }`
2 Answers

This can be easilly solved by putting that image inside of public folder and then referencing it like so: src="/{Your-Image.jpg}".

UPDATE

I got the image to load while using the <Redirect> tag. I am not sure why, but the issue was resolved when I switched my loader in my webpack config file from file-loader to url-loader. After making that switch, the app works appropriately. However, I don't really know what the true problem was :/

Related