Ad

Fonts Not Found With Nested Routes In React-router

I'm using React, React-Router and Webpack (with webpack-dev-server) and I'm having trouble loading custom fonts on nested routes.

Everything works fine on my shallow routes like /user, /group, etc., but when I have a nested route like /group/user, the custom fonts don't get loaded (404 error).

The Webpack build puts all the fonts in the root level as expected (with filenames like 7f690e503a254e0b8349aec0177e07aa.ttf), and when showing a route like /user, the fonts are loaded properly.

However, when in a nested route like /group/user, the browser tries to load the fonts from a URL like /group/7f690e503a254e0b8349aec0177e07aa.ttf, which doesn't exist.

I think that somewhere the font is assumed to be a relative path, but I don't know where.

How can I make the font paths be absolute paths rather than relative? Or is there another way to fix this?

Not sure if it matters, but I've defined my fonts as shown below in my styles.less file:

// Main font(s)
@font-face {
  font-family: 'Lato-Regular';
  src: url('../fonts/Lato-Regular.ttf') format('truetype');
}
Ad

Answer

In this case a possible solution is to add the base element to your pages. The base element allows you to specify a base URL to be used throughout the document for relative URL addresses. For example setting:

<base target="_blank" rel="nofollow noreferrer" href="http://www.youdomain.com/">

then you know that all relative paths should be relative to the root of your domain.

Ad
source: stackoverflow.com
Ad