Simoroshka
Simoroshka

Reputation: 349

Dynamic reference to a google font from react app

There are ways to include google fonts to the project (either through css import or link in the html head or with a help of webfontloader package), but what I would like to do is to have it on demand, based on specific page settings.

For example, the website is a blog platform. A user can specify a link to a google font for their page. When anyone is on their page that font is used. And when they go to another user's page, another font is loaded (that the other user specified).

Is there a way to do this?

EDIT: okay, I didn't think that the head can be modifiable since in my setup it was static. So far I found a couple of possible options:

  1. Use react-webfont-loader to load fonts
  2. Use react-helmet to specify everything in the head (also title of the page, for example).

Upvotes: 1

Views: 2705

Answers (2)

emarticor
emarticor

Reputation: 360

You could use the Web Font Loader library. It was codeveloped by Google and Typekit, and it's mainly designed to give you more control over font loading than what the Google Fonts API provides. A nice added bonus is that it also allows you to use it with a few other web font providers out of the box—Typekit and Google Fonts included, of course

In a nutshell it's somewhat of a wrapper around @font-face, so it would probably do what you're looking for, and provide some nice controls around going display while the font is being loaded.

The quick reference implementation would be:

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script> WebFont.load({ google: { families: ['Droid Sans', 'Droid Serif'] } }); </script>

Instead of having the logic inlined, you'd customize and expand the use of WebFont.load to accommodate the needs of your business logic, and then that could be bundled with your code.

Here's a link to the project: https://github.com/typekit/webfontloader

Hope this helps!

Upvotes: 1

Aniruddh Agarwal
Aniruddh Agarwal

Reputation: 917

Yes there's a way you can do this. You will have to take two inputs from user

  • Link to that Google Font

  • and the access specifier for that font

After these two details you can take the 2nd one as a variable to pass to your font-family font in this way:

style={{fontFamily: this.state.acessSpecifier}}

Upvotes: 1

Related Questions