Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router doesn't load images properly with nested routes

My route code looks like this:

    <Router history={browserHistory}>
        <Route path='/' component={AppContainer}>
            <IndexRoute component={Home}/>
            <Route path='/MyRYLA' component={MyRYLA} />
            <Route path='/gallery' component={PhotoViewer}/>
            <Route path='/about' component={AboutView}>
                <IndexRoute component={AboutRYLA}/>
                <Route path='/about/contact' component={Contact}/>
                <Route path='/about/directions' component={Directions}/>
                <Route path='/about/principles' component={Principles}/>
                <Route path='/about/faq' component={FAQ}/>
            </Route>
        </Route>
    </Router>

I have an image that renders within AboutView, so that each page under AboutView still has that image on it. But every time I navigate to a nested URL like '/about/directions', using browserHistory.push('/about/directions'), the image doesn't load. However, if I navigate to just '/about' using browserHistory.push('/about'), the image does load.

I do get an error in the console that says GET http://localhost:8080/about/af16977b21bb178d3bb328689d1ecd65.jpg 404 (Not Found). This looks to me like it is trying to get the image from a non-existent 'about' directory. How can I load the image and prevent React-Router from trying to access this image through a non-existent 'about' directory?

like image 492
jrademacher Avatar asked Mar 13 '17 20:03

jrademacher


2 Answers

Is is possible you're using a relative path in your image tag?

Something like <img src="af16977b21bb178d3bb328689d1ecd65.jpg" /> instead of <img src="/af16977b21bb178d3bb328689d1ecd65.jpg" />

The inital/ in the src attribute makes the image load from the root of the website.

like image 195
iamalismith Avatar answered Nov 15 '22 17:11

iamalismith


This is what ended up helping me get my images to work with nested routes in React:

<head>
    <base href="/">
</head>
like image 34
John Harden Avatar answered Nov 15 '22 16:11

John Harden