React-router does not load css for subpages when updating

I am trying to configure react-routerfor my first React webapp, it works, except that css does not load for my sub-pages when updating pages.

However, it only works on one level, for example /dashboard, but css does not load for/components/timer

Here is what my file looks like index.jsx

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?

+4
source share
4 answers

I also had this problem when my application did not load stylesheets and the like. However, I imported my assets directly to the entry point index.html.

, .

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

:

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

, , .

FYI create-react-app.

+13

!

HTML:

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

, URL-, .

+3

script css - 404. - /components/* , .

, , Css... css jsx , :) SASS LESS css bundle.css grunt gulp. bundle.css index.html. css - , .scss .less, bundle.css .

, .

,

0

If you use the create-react-app workflow, put the assets in a shared 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, placing them together 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 a shared folder

When to use a public folder

0
source

Source: https://habr.com/ru/post/1659837/


All Articles