React-router not loading css for nested pages on refresh
Asked Answered
A

9

39

I'm trying to setup a react-router for my first React webapp, it seems to be working except that the css doesn't load for my nested pages when I refresh the pages.

However it works for just one level e.g /dashboard but the css won't load for /components/timer

Here is what my index.jsx file looks like

import './assets/plugins/morris/morris.css';
import './assets/css/bootstrap.min.css';
import './assets/css/core.css';
import './assets/css/components.css';
import './assets/css/icons.css';
import './assets/css/pages.css';
import './assets/css/menu.css';
import './assets/css/responsive.css';

render(
  <Router history={browserHistory}>
    <Route path="/" component={Dashboard}/>
    <Route path="/components/:name" component={WidgetComponent}/>
    <Route path="*" component={Dashboard}/>
  </Router>,
  document.getElementById('root')
);

Any idea why?

Abbotsun answered 4/11, 2016 at 15:10 Comment(5)
Are you getting 404s on those .css files when you reload? Is your web server pointing all / and /components/:name to your index.js where you load react and all related files?Yasmin
@Yasmin am getting 404, it tries to load the css and scripts as http://localhost:3000/components/assets/js/jquery.slimscroll.js instead of http://localhost:3000/assets/js/jquery.slimscroll.jsAbbotsun
@Yasmin how do I point my webserver to /components/:name?Abbotsun
it depends on the webserver you are using. Apache uses .htaccess file for pretty links, while ExpressJS uses a RegExp to match your routesYasmin
@AdetiloyePhilipKehinde How did you solve this?Sheehy
S
93

I had this problem too, where my app wasn't loading style sheets and the like. However, I was importing my assets directly into my index.html entry point.

By replacing the links with absolute paths as per this documentation, my problem was resolved.

For me, this meant changing

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

to this:

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

I'm not sure if the same thing would work for your import statements, but it is worth a shot.

FYI I'm using the project layout from create-react-app.

Spencerianism answered 25/6, 2017 at 3:4 Comment(2)
Thanks sonarforte, for those using Webpack with the html webpack plugin to generate your index.html files I was able to solve this issue by telling Webpack where to place the output file in my config file. The object looked like this: output: { publicPath: "/" }Packard
worked for me! it was all about removing the dot before the path....Trig
S
40

Found it!

Add the HTML Element:

<base href="/" /> <!-- for local host -->

to your index page to set a base case for your URL so all else will follow suite.

Sheehy answered 4/3, 2017 at 19:12 Comment(2)
Worked for me as of 10/2020Pincas
Perfect solution for nextjs or any folder structure architectureVervet
L
16

I added

<base href="/" /> <!-- for local host -->

to my index.html head

And it is resolved.

Libelee answered 10/8, 2019 at 23:9 Comment(0)
R
7

The simplest solution is here (Need to change index.html only)

Just use %PUBLIC_URL% before every CSS or JS file.

You can check an example of %PUBLIC_URL% in index.html file if you created react app through create-react-app.

<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

One thing is must: your CSS files and js files should be under a public directory.

Rael answered 28/4, 2020 at 4:46 Comment(0)
B
6

If you are using create-react-app workflow, put the assets under public folder and use the special variable PUBLIC_URL.

Inside index.html use %PUBLIC_URL%:

<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

Inside JS/JSX files use process.env.PUBLIC_URL:

render() { // Note: this is an escape hatch and should be used sparingly! // Normally we recommend using import for getting asset URLs // as described in “Adding Images and Fonts” above this section. return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; }

Recommended Approach:
import stylesheets, images, and fonts from JavaScript by placing it along with src files.

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image

console.log(logo); // /logo.84287d09.png

function Header() {
   // Import result is the URL of your image
   return <img src={logo} alt="Logo" />;
}

export default Header;

Adding assets to public folder

When to use public folder

Batwing answered 22/2, 2018 at 18:49 Comment(0)
H
1

I know its a bit old thread, but ill share my solution here. Its a solution for setup that uses webpack instead create-react-app.

I found every other solution suggests to change the <link path in the html file. But like in my case webpack handles the asset linking.

I faced the same problem today. Routes like /some_route works but - /some_route/second_level it doesn't, leaving behind a message in console stating -

Refused to apply style from 'http://localhost:8080/some_route/some_style.css'.

I fixed this problem by updating my webpack.config.js file

output: {
    filename: 'build.js',
    path: path.join(__dirname, '/dist'),
    publicPath: '/',         ////// <-- By adding this line
}

Hope it helps someone. Thanks!

Helvetii answered 13/3, 2019 at 22:30 Comment(2)
I don't see a webpack,config.jsThreepiece
Sry, but this is the output configuration part of webpack.config.js. The rest of the webpack.config.js is not the subjectHelvetii
Y
0

Your script is not loading your css due to the 404 errors. Your webserver is not redirecting all /components/* request to index file and then routing to your view via react.

But now, specifically about fixing your css issues... In the past, I've struggled with the css imports in jsx files, so you are not alone :) Instead, I've chosen to use SASS or LESS to compile my css to a bundle.css file with grunt or gulp. Then load that bundle.css directly on my index.html file. One neat trick about using css compilers is every time you change a .scss or .less file, your bundle.css will get updated.

Hope I pointed you in the right direction.

Cheers,

Yasmin answered 4/11, 2016 at 16:4 Comment(1)
thanks Jorge but loading bundle.css won't solve the problem of webserver not redirecting /components/* to index file ?Abbotsun
B
0

I know this is weird , but if you use [email protected] ,delete it and install [email protected] react-router have many incompatibilities with history version 5 . for me it's worked.

Basile answered 14/3, 2021 at 17:24 Comment(0)
M
0

If you built your app using webpack,

Change

...
output: {
     publicPath: "./",
     ...
},
...

to

...
output: {
     publicPath: "/",
     ...
},
...

Cheers

Medorra answered 16/4, 2024 at 17:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.