React BrowserRouter routes with a parameter are not loading the CSS files

I have a BrowserRouter set up in my main.js file and it switches between the desired pages when I visit the respective URLs

index.html

<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/main.css" />

main.js

return (
    <StateContext.Provider value={state}>
      <DispatchContext.Provider value={dispatch}>
        <BrowserRouter>
          <Header />
          <Switch>
            <Route path="/ingredient">
              <IngredientPage />
            </Route>
            <Route path="/ingredientsList/:id" exact>
              <IngredientListPage />
            </Route>
            <Route path="/create-recipe">
              <CreateRecipe />
            </Route>
            <Route path="/list-recipes">
              <ListRecipes />
            </Route>
            <Route>
              <NotFound />
            </Route>
          </Switch>
          <Footer />
        </BrowserRouter>
      </DispatchContext.Provider>
    </StateContext.Provider>
  );

My issue is that the CSS files are loaded with the wrong URL whenever I visit a route that has a parameter.

Example 1 (expected) I visit a route URL without a parameter http://localhost:3000/ingredient The CSS files are successfully loaded e.g. http://localhost:3000/css/style.css and styling applied to the page

Example 2 (unexpected) I visit a URL with a parameter http://localhost:3000/ingredientsList/1 The page loads but no styling is applied. CSS files are requested from the URL up to where the parameter is added e.g. http://localhost:3000/ingredientsList/css/style.css

Any idea what’s causing the URL to change here and how it can be fixed?

EDIT: Ok, I have it working now by hardcodeing the URL in the index.html

<link rel="stylesheet" href="http://localhost:3000/css/style.css" />
<link rel="stylesheet" href="http://localhost:3000/css/main.css" />

Not exactly ideal though as the base URL is now hardcoded

Answer

So the issue here is just that your css was being accessed from a relative path instead of the root path.

I bet your link looked like this:

<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/main.css" />

Which will start at the current directory and then look for the css directory, so when you’re in a deeper file path it’s looking at the wrong place.

What you need is something like this:

<link rel="stylesheet" href="/css/style.css" />
<link rel="stylesheet" href="/css/main.css" />

The leading / says to go back to the root directory and then access the css directory from there.

The fact that it happened when you were on a parameter page might mean that your css href was "../css/main.css" or "./css/main.css" or something. In any case, changing it to what I’ve suggested should fix your problem without hardcoding the base url.

Leave a Reply

Your email address will not be published. Required fields are marked *