Giter Club home page Giter Club logo

react-with-async-fonts's Introduction

react-with-async-fonts

npm Version Build Status Coverage Status Greenkeeper badge

React module for working with async loaded custom web fonts, based on fontfaceobserver.

Note: version 4.x introduces breaking changes with new API. It addresses bunch of issues, including canceling promises, better performance, and TS typings.

Quick Start

  1. Install react-with-async-fonts:

npm:

npm install --save react-with-async-fonts

yarn:

yarn add react-with-async-fonts
  1. Wrap your root component with FontObserver:

Set prop with font name. You can access it later in FontSubscriber to check if it's ready.

import { FontObserver } from 'react-with-async-fonts';
import { render } from 'react-dom';
import App from './app';

render(
  <FontObserver openSans="Open Sans">
    <App />
  </FontObserver>,
  document.getElementById('root'),
);
  1. Wrap your target with FontSubscriber component:

Tip: you can also use withFonts API if you're really into HoCs.

Note that FontSubscriber uses children render prop. Provided function would be called with single argument which is an object with loaded font keys.

import { FontSubscriber } from 'react-with-async-fonts';

const Heading = ({ children }) => (
  <FontSubscriber>
    {fonts => (
      <h1 className={fonts.openSans ? 'opens-sans-font' : 'system-font'}>
        {children}
      </h1>
    )}
  </FontSubscriber>
);

export default Heading;

API

FontObserver component

import { FontObserver } from 'react-with-async-fonts';
Prop Type Description
text string fontfaceobserver's .load text options
timeout number fontfaceobserver's .load timeout options
[key] Font | string Font family string or a Font object.

FontSubscriber component

import { FontSubscriber } from 'react-with-async-fonts';
Prop Type Description
children (fonts: Object) => React.Element<any> Children render function. Accepts object with loaded font. Once ready, it would contain object of Font type.

withFonts HoC

import { withFonts } from 'react-with-async-fonts';
Argument Type Description
component React.ComponentType<any> Component to wrap with HoC. Injects fonts object.

Font type

type Font = {
  family: String,
  weight?:
    | 'normal'
    | 'bold'
    | 'bolder'
    | 'lighter'
    | '100'
    | '200'
    | '300'
    | '400'
    | '500'
    | '600'
    | '700'
    | '800'
    | '900',
  style?: 'normal' | 'italic' | 'oblique',
  stretch?:
    | 'normal'
    | 'ultra-condensed'
    | 'extra-condensed'
    | 'condensed'
    | 'semi-condensed'
    | 'semi-expanded'
    | 'expanded'
    | 'extra-expanded'
    | 'ultra-expanded',
};

Examples

Heads up! Each example requires wrapping your app with FontObserver:

import React from 'react';
import { render } from 'react-dom';
import { FontObserver } from 'react-with-async-fonts';
import App from './app';

render(
  <FontObserver montserrat="Montserrat">
    <App />
  </FontObserver>,
  document.getElementById('root'),
);

Basic with FontSubscriber

import React from 'react';
import { FontSubscriber } from 'react-with-async-fonts';

const Heading = ({ children }) => (
  <FontSubscriber>
    {fonts => (
      <h1 className={fonts.montserrat && 'montserrat-font'}>{children}</h1>
    )}
  </FontSubscriber>
);

export default Heading;

Basic with withFonts

You can use withFonts HoC if you want to compose your component. Please note it uses same FontSubscriber under the hood.

import React from 'react';
import { withFonts } from 'react-with-async-fonts';

const Heading = ({ children, fonts }) => (
  <h1 className={fonts.montserrat && 'montserrat-font'}>{children}</h1>
);

export default withFonts(Heading);

With styled-components

Most elegant way of using it with styled-components is withFonts HoC.

import styled from 'styled-components';
import { withFonts } from 'react-with-async-fonts';

const Heading = styled.h2`
  font-weight: 300;
  font-family: ${props =>
    props.fonts.montserrat
      ? '"Open Sans", sans-serif'
      : 'Helvetica, sans-serif'};
`;

export default withFonts(Heading);

Nested FontObserver

You can nest FontObserver to merge fonts. Children instances overrides parent if font with same code was defined.

import { FontObserver, FontSubscriber } from 'react-with-async-fonts';

const Article = ({ title, children }) => (
  <FontObserver roboto="Roboto">
    <FontObserver ptSans="PT Sans">
      <FontSubscriber>
        {fonts => (
          <article>
            <h1 className={fonts.roboto ? 'roboto' : 'sans-serif'}>{title}</h1>
            <p className={fonts.ptSans ? 'ptsans' : 'serif'}>{children}</p>
          </article>
        )}
      </FontSubscriber>
    </FontObserver>
  </FontObserver>
);

export default Article;

Custom fontfaceobserver options

You can provide text and timeout options for fontfaceobserver's .load method with same props.

import { FontObserver, FontSubscriber } from 'react-with-async-fonts';

const Heading = ({ children }) => (
  <FontObserver text={children} timeout={2500} roboto="Roboto">
    <FontSubscriber>
      {fonts => <h1 className={fonts.roboto && 'roboto'}>{children}</h1>}
    </FontSubscriber>
  </FontObserver>
);

export default Heading;

License

MIT © Sergey Bekrin

react-with-async-fonts's People

Contributors

greenkeeper[bot] avatar remownz avatar sbekrin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-with-async-fonts's Issues

3.1.0 throws error with create-react-app

Hi @sergeybekrin,

version 3.1.0 throws a dependency error when using with create-react-app:

webpackMissingModule node_modules/react-with-async-fonts/lib/index.js:21 ./node_modules/react-with-async-fonts/lib/index.js.Object.defineProperty.value node_modules/react-with-async-fonts/lib/index.js:21 ./node_modules/react-with-async-fonts/lib/index.js node_modules/react-with-async-fonts/lib/index.js:27

there is no problem with 3.0.3

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

An in-range update of enzyme is breaking the build 🚨

There have been updates to the enzyme monorepo:

    • The devDependency enzyme was updated from 3.8.0 to 3.9.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the enzyme group definition.

enzyme is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/react-dom is breaking the build 🚨

Version 15.5.6 of @types/react-dom just got published.

Branch Build failing 🚨
Dependency @types/react-dom
Current Version 15.5.5
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As @types/react-dom is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

win10 ie11 performance

i used your hoc for several components, e.g headings, texts etc. All works fine in chrome, firefox safari, edge and ie11 (win7). With ie11 (win10) i had massive performance issues sometimes with full browser crash. I profiled and found heavy cpu usage for your load function:https://github.com/sergeybekrin/react-with-async-fonts/blob/20614b2229509783a1d76ff62216c518ea9fc32e/src/helpers.ts#L8
I think the heavy load is caused by lots of fontfaceobserver instances. I ended up by using withAsyncFont for my App component only and setting global classNames.
Maybe u could check and confirm this behavior?!

Not working with create-react-app

Getting this when trying to create production build:

Failed to minify the code from this file: 
	./node_modules/react-with-async-fonts/dist/font-subscriber.js:3 

Also tried importing from /lib/ directory but then getting:
Uncaught TypeError: hoist_non_react_statics_1.default is not a function

What does it do ?

Hi,

I'm using custom fonts for my website. For now, I use base64 string so that it forces the browser to load the font before displaying anything on the screen. It avoids the font flickering on load but I think this library might be a better suit. But I can't seem to find what it does? Sorry if that's obvious to some.

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react was updated from 16.6.0 to 16.6.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v16.6.1

16.6.1 (November 6, 2018)

React DOM

  • Fallback should not remount every time a promise resolves. (@acdlite in #14083)
  • Fix bug where Suspense keeps showing fallback even after everything finishes loading. (@acdlite in #14083)
  • Fix unresolved default props in lifecycle methods of a lazy component. (@gaearon in #14112)
  • Fix bug when recovering from an error thrown during complete phase. (@gaearon in #14104)

Scheduler (Experimental)

  • Switch from deadline object to shouldYield API. (@acdlite in #14025)
FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/react is breaking the build 🚨

Version 15.0.25 of @types/react just got published.

Branch Build failing 🚨
Dependency @types/react
Current Version 15.0.24
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As @types/react is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

setState(...): Can only update a mounted...

I some cases a component is unmounted before font loading is finished. I think you need a componentWillUnmount method which resolves font loading immediately otherwise you get the warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the WithAsyncFontsHoC component. see https://github.com/sergeybekrin/react-with-async-fonts/blob/b8d8b8c6a57ff6dc34e6e9baa89ee863df11e83d/src/index.ts#L68

An in-range update of @types/react is breaking the build 🚨

The devDependency @types/react was updated from 16.7.0 to 16.7.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/enzyme is breaking the build 🚨

Version 2.8.1 of @types/enzyme just got published.

Branch Build failing 🚨
Dependency @types/enzyme
Current Version 2.8.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As @types/enzyme is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of @types/enzyme is breaking the build 🚨

Version 2.8.4 of @types/enzyme just got published.

Branch Build failing 🚨
Dependency @types/enzyme
Current Version 2.8.3
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As @types/enzyme is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.