I'm developing a small blog app as a portfolio project and have run into something weird.
I have a Blog component mounted at http://localhost:3000/blog. Works great. I reference a few images in the ~/public folder, using src="image.png". This becomes http://localhost:3000/image.png which finds the image in the public folder as expected.
When I set up another route, to view an individual post, at http://localhost:3000/blog/1, it breaks the image link. Instead src="image.png" evalutates to http://localhost:3000/blog/image.png which doesn't exist. Why is that?
I've seen answers related to using process.env.PUBLIC_URL + "image.png" but that's undefined in my app. (created with 'create-react-app'). I tried making a .env file in the root directory with PUBLIC_URL=http://localhost:3000 but that hasn't done anything. (Yes I restarted the build script.)
As a workaround I created a module containing export const baseURL = 'http://localhost:3000/'; and am using baseURL + image.png but I'm wondering about the 'proper' React way to do this, and why the /blog is inserted into the URL only when the URL contains a parameter.
Here is the main component where I do the routing:
const Main = (props) => {
return (
<div>
<Header />
<Switch location={props.location}>
<Route path='/home' component={Home} />
<Route exact path='/blog' component={Blog} />
<Route path='/blog/:postId' component={Blog} />
<Route path='/about' component={About} />
<Redirect to="/home" />
</Switch>
<Footer />
</div>
)
}