oldo.nicho
oldo.nicho

Reputation: 2289

Dynamically set font with React

I am making a React app that will be used by a variety of different users. Each user has the ability to set the google font that they want the app to render in and the font-family will be returned as part of a settings call that is made when the app initially loads. This font name is stored within the Redux store.

What I'd like to do is to request the correct font file from Google depending on what font-family is set by the user and then inject into the app's css for that particular font:

h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: 'set-font', helvetica, sans-serif;
}
p, div {
  font-family: 'set-font', helvetica, sans-serif;
}

I have done a fair bit of searching and I can't find anything about what I'm trying to achieve despite it seeming like a fairly common scenario.

I've come across webfontloader which seems to be a step in the right direction for fetching the font file.

Upvotes: 1

Views: 2460

Answers (1)

oldo.nicho
oldo.nicho

Reputation: 2289

Answer ended up being very simple.

Use the webfontloader library then in componentWillReceiveProps() check once font-family has been returned by settings call, then run:

WebFont.load({
  google: {
    families: ['font-family-from-settings-call']
  }
});

And apply this style to app as:

const appStyle = {
  fontFamily: 'font-family-from-settings-call'
};

Upvotes: 2

Related Questions