1

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>
        )
}
yhghy
  • 141
  • 2
  • 10
  • 1
    [See this thread](https://stackoverflow.com/questions/47196800/reactjs-and-images-in-public-folder). Essentially, you should access the public folder in CRA projects with a leading slash (`src="/image.png"`). More broadly speaking, its almost always better to instead keep static images in an `assets` directory inside the `src` directory and import at the top of the file where they are needed for improved error handling and minification. – lawrence-witt Nov 11 '20 at 21:01

0 Answers0