machve
machve

Reputation: 71

Dynamically add google font and custom font reference React

I am building an application where people can create banners and I have a list of fonts. This list contains web-safe fonts, custom fonts and google fonts. For each text element the user can choose a font.

For each of this selected fonts I need to append to head either link referring to google fonts or add a style tag with font-face referring to the custom font that is being hosted by us. Overall the list is more than 1000 fonts long.

So for custom font I want to add

<style>
@font-face {
  font-family: "somefamily";
  font-style: normal;
  font-weight: 400;
  src: url("https:someurl.ttf")
}
</style>

and for each google font

<link href="https://fonts.googleapis.com/css?family=somefamily:400,600,700,800" rel="stylesheet" type="text/css">

I tried to make it work with React helmet but I don't think it is the way to go or at least I didn't manage to make it dynamic so it only shows the link or style tag for the selected font.

I also tried webfontloader but that one is piling the fonts on top of each other.

Same goes for creating the tags in JS and then appending it to the head

          let url = "https://fonts.googleapis.com/css?family=";
          url += font.name.replace(" ", "+");
          url += ":" + font.weights.join(",");
          url.replace("regular", "400");
          let link = document.createElement('link')
          link.href = url;
          link.rel = "stylesheet";
          link.type =  "text/css";
          document.head.appendChild(link);

In this codesandbox https://codesandbox.io/s/billowing-river-khqob?file=/src/App.js I made a small example with googlefonts that are piled up every time user chooses new one.

Is there a way how to dynamically get the fonts that user selected without keeping the previous ones? Is it possible to somehow add it as css instead with packages like fex. emotion?

Thank you for your help

Upvotes: 4

Views: 4548

Answers (1)

Related Questions