Skip to content

Instantly share code, notes, and snippets.

@jakewtaylor
Last active November 28, 2018 23:19
Show Gist options
  • Save jakewtaylor/ad2ef4dcb5548ac716f0faacf8c2c74d to your computer and use it in GitHub Desktop.
Save jakewtaylor/ad2ef4dcb5548ac716f0faacf8c2c74d to your computer and use it in GitHub Desktop.
GoogleFontLoader React Component.

GoogleFontLoader

This is a really simple component that can automatically handle loading Google fonts for you.

You simply pass it a config array and it will load the fonts for you by appending a <link /> tag to the document head. It will update itself if the config changes, and will remove itself on unmount.

Example usage:

const App = () => (
  <>
    <GoogleFontLoader fonts={[
      {
        font: 'Roboto',
        weights: [400],
      },
      {
        font: 'Roboto Mono',
        weights: [400, 700],
      },
    ]} />

    <p style={{ fontFamily: 'Roboto Mono, monospaced' }}>This will be in Roboto Mono!</p>
    <p style={{ fontFamily: 'Roboto, sans-serif' }}>This will be in Roboto!</p>
  </>
);
import React from 'react';
class GoogleFontLoader extends React.PureComponent {
link = null;
createLink = () => {
const { fonts } = this.props;
const families = fonts.reduce((acc, font) => {
const family = font.font.replace(/ +/g, '+');
const weights = font.weights.join(',');
acc.push(`${family}:${weights}`);
return acc;
}, []).join('|');
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = `https://fonts.googleapis.com/css?family=${families}`;
return link;
}
appendLink = () => document.head.appendChild(this.link);
removeLink = () => document.head.removeChild(this.link);
replaceLink = () => {
this.removeLink();
this.link = this.createLink();
this.appendLink();
}
componentDidMount () {
this.link = this.createLink();
this.appendLink();
}
componentDidUpdate (prevProps) {
if (JSON.stringify(prevProps.fonts) !== JSON.stringify(this.props.fonts)) {
this.replaceLink();
}
}
componentWillUnmount () {
this.removeLink();
}
render = () => null;
};
export default GoogleFontLoader;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment