`Error occurring with React-router when refreshing nested pages causing CSS not to load`

Setting up a react-router for my first React webapp has been a bit tricky. It seems to be functioning properly except for the issue with CSS not loading on nested pages when they are refreshed.

The CSS works fine for single level paths like /dashboard, but it doesn't load for paths like /components/timer.

Here is an excerpt from my index.jsx file:

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 thoughts on why this might be happening?

Answer №1

Having faced a similar issue, I encountered a problem where my application was not loading style sheets and other assets. The cause of this issue was my direct import of assets into the index.html entry point of my app.

Following the instructions provided in this documentation on using absolute paths instead of relative links solved my problem effectively.

For me, this required changing

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

to:

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

While I cannot guarantee that this solution will work for your import statements, it is worth trying out.

For reference, I am using the project layout from create-react-app.

Answer №2

Discovered!

Insert the following HTML Element:

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

into your main webpage to establish a base URL so that everything else will align accordingly.

Answer №3

After updating my index.html file, I included the following line in the head section:

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

This addition resolved the issue I was experiencing.

Answer №4

The most straightforward solution can be found right here (Just make changes to index.html)

All you need to do is add %PUBLIC_URL% before each CSS or JS file.

If you used create-react-app to create your react app, you can see an example of %PUBLIC_URL% in the index.html file.

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

Remember: Your CSS and JS files must be located within a public directory.

Answer №5

If you are utilizing the create-react-app workflow, place your assets in the public folder and utilize the special variable PUBLIC_URL.

When working inside index.html, utilize %PUBLIC_URL%:

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

Within your JS/JSX files, use process.env.PUBLIC_URL:

render() {
  // Take note: only use this sparingly and as a last resort!
  // It's generally recommended to use the import method for accessing asset URLs
  // as explained in the “Adding Images and Fonts” section above.
  return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}

Preferred Method:
Import stylesheets, images, and fonts in JavaScript by placing them alongside your source files.

import React from 'react';
import logo from './logo.png'; // Inform Webpack that this JS file utilizes this image

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

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

export default Header;

Guidelines for adding assets to the public folder

When it is appropriate to use the public folder

Answer №6

Although this thread is a bit dated, I wanted to contribute my solution using webpack instead of create-react-app.

Many solutions out there recommend changing the path in the html file using <link, but in my case, webpack handles asset linking.

Today, I encountered the same issue where routes like /some_route were working fine, but /some_route/second_level was not, resulting in a message in the console that read:

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

I was able to resolve this issue by making an adjustment to my webpack.config.js file:

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

Hopefully, this solution can assist someone else. Thank you!

Answer №7

Your issue with the script not loading your css is likely stemming from the 404 errors occurring. Your web server may not be properly redirecting all requests for /components/* and routing them to your view via react.

When it comes to fixing your css problems, I've had my own struggles with css imports in jsx files before, so you're definitely not alone! Personally, I prefer using SASS or LESS to compile my css into a bundle.css file using grunt or gulp. Then, I simply load this bundle.css directly into my index.html file. One advantage of using css compilers is that your bundle.css will automatically update whenever you make changes to your .scss or .less files.

I hope this information helps guide you in the right direction.

Best regards,

Answer №8

It may seem unconventional, but if you have been using [email protected], consider removing it and switching to [email protected]. I found that react-router can have compatibility issues with history version 5, but this alternative worked for me.

Answer №9

If your application was constructed using webpack,

Modify

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

to

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

Cheers

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to trigger a modal popup when hovering over a Bootstrap 5 card?

After coming across a handy template online, I decided to implement a modal pop-up feature when hovering over cards using Bootstrap 5. Here's what I have so far: class SavedEpisodes extends Component { $(function() { $('[data-toggle=&qu ...

Having difficulty sending emails with attachments using AngularJS

While using Angular, I encountered an issue when sending an email with an attachment. The response I received contained the data code of the file instead of its actual format. See example: https://i.stack.imgur.com/vk7X8.png I am unsure what is causing t ...

Upon commencing the project, an error arises with reactstrap when attempting to import the library

Issue with Error console in node_modules/reactstrap/lib/index.js: SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:73:18) at wrapSafe (node:internal/modules/cjs/loader:1176:20) ... Node.js v18. ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

Learn how to dynamically update the marker's position as it is being dragged using React-Leaflet

Currently, I am working with React-leaflet to fetch a specific position. I have implemented a search input field where users can enter addresses to place the marker on the map using an API. However, I am looking for a way to enable more precise movement of ...

Tips for aligning text vertically in flexbox arrangements

As I work on building my portfolio, I have implemented links as buttons using flexbox to make responsiveness easier. The height of these flexboxes is set dynamically using JavaScript with percentages. Despite trying various suggestions, none of them provi ...

Combining several btn-group and btn-group-vertical elements within each other

I am looking to create a button grid resembling a numpad for my project. I am utilizing angular and bootstrap 5 and thought of using btn-group and btn-group-vertical for this purpose. While this setup would work for a regular button grid, I need to have t ...

Unique layout design that organizes calendar using nested divs with flexbox - no

I am having difficulties achieving the desired outcome with my calendar header layout implemented using flexbox for the years, months, and days. What could be the issue? Is it due to the structure of the HTML or is there something missing in the CSS? The ...

Proper format for implementing recursive API call in React using Redux-Thunk

Our goal is to create a recursive API call based on the number of records returned in the response. For instance, if the response contains 10 records out of a total of 20, we should make another API call for the next 10 records. What is the best approach ...

Unable to apply 100% height to flex child element

When it comes to creating a layout for my website, I have a simple idea in mind. I want the body content to take up at least 100% of the height of the page. This setup works perfectly on desktop screens, but when I switch to a mobile view (which changes th ...

Setting Up One Stylesheet Based on Local Preferences

I am working on positioning translated text on a webpage. The word NEW in English and NOUVEAU in French need to be centered below a graphic. Since the words have different lengths, I am considering using absolute positioning. The challenge is setting the l ...

When the browser window is minimized, the top section of the website becomes concealed

For the past few weeks, I have been working on creating a new website. The progress is looking good overall, but there is one issue that I have encountered. When viewing my website in a browser window smaller than the actual webpage size, the top menubar ...

Having trouble with Autocomplete Mui Testing? It seems like simulating a change isn't doing the

I'm having trouble updating a state's component using enzyme to simulate an onChange event. Below is the code for the component in question: Component: import React, { useState } from 'react'; import TextField from '@material-ui/c ...

row-1 css classes on the top in a project built with Blazor

I'm currently working on customizing the standard layout provided in Blazor projects like WASM or server, but I'm a bit perplexed by the top-row px-4 css classes. Within the HTML code that appears to define the top row/header section is this sni ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...

How can you show images in Nextjs using a browser if they are not saved in the /public folder?

In my current project, I am utilizing Next.js as a full-stack framework with API route handlers in the backend. One issue I have encountered is related to storing images under the /uploads directory using the fs.writeFile method and only saving the path to ...

Ensuring your React Web Application runs indefinitely

After developing a web application with the React framework, I successfully ran it on localhost using the npm start command. I then transferred the code to a server on AWS running Ubuntu 14.04 and managed to run the application with the npm command. Howev ...

Getting the value of a checkbox from a MySQL database

Is there a way to print the entire contents of a textarea without any scroll bars, so that all text entered is visible? Currently, only the last few lines are showing when printed. I need the textarea to automatically resize for printing. <textarea cla ...

Having difficulty adding items to the shopping cart

While working on a simple checkout system using django and react, I encountered an issue. Upon clicking the add to cart button, instead of adding the item to the cart as intended, I receive a 404 page not found error. I suspect that the problem may lie in ...

Customizing Bootstrap css variables for a unique design

Currently, I'm working on tweaking the data-bs-theme in Bootstrap 5.3. My goal is to adjust the pre-defined CSS variables of the Bootstrap dark theme and refresh the color palette. Specifically, I want to change the shade of blue for my blue button (b ...