Fra
Fra

Reputation: 62

Images disappear in production build of React because the wrong path is generated

this is my first time posting here.
I am having a problem with how the production build paths to my images are generated when I run npm run build.

I have some logos to display in one of my React components, which show properly in the local server... the problem arises when I deploy to Netlify.

This is the code I use to get them dynamically:

currentProject.icons.map(el => {
  return (
    <div key={el.id} className={styles.logo}>
      <div
        className={styles["logo-wrap"]}
        style={{ margin: ".3rem 0" }}
      >
        {el.icon}
        <p>{el.tag}</p>
      </div>
    </div>
  );
})}

This is the result in localhost:
Logos locahost

But this is the result in production:
Production build logos

Now, I noticed that in the production build the image src is wrong (./ instead of ../) as when I modify the path in the devtools, the correct image pops up.

My images are in public/Icons but I am importing them to my projects properties so I can render them dynamically.

Before:
enter image description here

After I add a . to the file path:
enter image description here

This is the folders structure:
enter image description here

Right now I was just testing with the React logo, but before I was also trying to import them from src/assets/Logos, but the result is the same in localhost.

How can I fix this problem?

Upvotes: 2

Views: 1527

Answers (1)

Fra
Fra

Reputation: 62

I solved this. Apparently, despite my Netlify production build having a __redirects file specifying that the entry point was /* /index.html 200, to have all the React Router subroutes working properly, I was missing <base href="/" /> within the <head> tags in public/index.html.

Adding this has fixed the image paths and some sub-routing issues (like accessing them directly from a link).

Upvotes: 2

Related Questions