philale
philale

Reputation: 437

React Router: Stylesheet not working on routes with URL parameters

I have set up a project with React and React Router. The general structure looks like this:

This is the html page:

<html lang="en">
  <head>
    <!-- other tags ... -->
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

This is the React Router structure:

//imports (createBrowserRouter, etc.)

export default function App(props){
    const router = createBrowserRouter([
        {
            path: "/",
            element: <Root/>,
            children: [
                {
                    path: "watch/:id", //URL param is the problem!
                    element: <Watch/>,
                    loader: watchLoader
                }
            ]
        }
    ])

    return (
        <RouterProvider router={router} />
    )
}

I need to note, that the React side of the application works fine. The URL parameter in watch/:id is the problem. If I remove it, the style gets applied to the site. I have no idea why it is not working.

Intuitively I thought that the style would get applied to all of the html pages content. In the end it is always the same html where the React components are inserted, so they should stick to the style.

Upvotes: 1

Views: 918

Answers (1)

Drew Reese
Drew Reese

Reputation: 202696

React apps are technically Single Page Apps. I suspect when requesting a "nested page" the server is correctly serving up the root index.html file to the browser... BUT the page is trying to load the stylesheet relative to the nested pathname, i.e. from "/watch/someId".

Try to use an absolute path.

<link rel="stylesheet" href="/styles.css">

Upvotes: 2

Related Questions