React Router: Stylesheet does not work for routes with dynamic URL parameters
P粉618358260
P粉618358260 2024-03-21 20:02:05
0
1
294

I have set up a project using React and React Router. The overall structure is as follows:

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 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 should note that the React side of the application works fine. The URL parameter in watch/:id is the problem. If I remove it, the styles are applied to the site. I don't know why it doesn't work.

Intuitively I think this style will be applied to all html page content. Finally, it is always the same html inserted into React components, so they should follow the styling.

P粉618358260
P粉618358260

reply all(1)
P粉254077747

React applications are technically single-page applications. I suspect that when a "nested page" is requested, the server is correctly serving 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 absolute paths.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template