react-create-keyframe

Helper to create and render keyframes on-demand in React

Stars
2

react-create-keyframe

A simple helper to create and render keyframes on on-demand. It (optionally) utilises React's new style hoisting feature when available.

Note: Style hoisting requires a canary version of React. Install via react@canary.

Installation

# npm
npm i --save react-create-keyframe
# yarn
yarn add react-create-keyframe
# pnpm
pnpm add react-create-keyframe

The Gist

import * as React from 'react'
import { createKeyframe } from 'react-create-keyframe'

const [animationName, node] = createKeyframe({
  from: {
    backgroundColor: 'red',
  },
  to: {
    backgroundColor: 'blue',
    transform: 'rotate(360deg)',
  },
})

function Component() {
  return (
    <>
      {node}
      <div
        style={{
          width: 50,
          height: 50,
          backgroundColor: 'red',
          animationName,
          animationDuration: '1s',
          animationIterationCount: 'infinite',
        }}
      />
    </>
  )
}

API Reference

createKeyframe

The only export of this package. It takes a keyframe style object and an optional nonce and returns both the keyframe name as well as a single React <style> node.

It converts camel case properties to dash case equivalent, but it does not add units to numbers.

Parameter  Type  Description
keyframe Keyframe   A keyframe style object
nonce string? (optional) nonce string

Keyframe

Partial<Record<'from' | 'to' | `${number}%`, CSSProperties>>

Example

const keyframe = {
  // equivalent to 0%
  from: {
    color: 'red',
  },
  '50%': {
    color: 'green',
  },
  // equivalent to 100%
  to: {
    color: 'blue',
  },
}

const [animationName, node] = createKeyframe(keyframe)

Recipes

Adding Units

If you want units to be added to your properties automatically, you can create your own helper or utilise existing packages such as fela-plugin-unit.

Note: Most fela plugins are isolated and do not require fela to be installed or used.

import { createKeyframe, Keyframe } from 'react-create-keyframe'
import unit from 'fela-plugin-unit'

// further customise by passing a config object to the plugin
const addUnits = unit()

const keyframe = {
  from: {
    fontSize: 16,
  },
  to: {
    fontSize: 20,
  },
}

createKeyframe(addUnits(keyframe))

License

react-create-keyframe is licensed under the MIT License. Documentation is licensed under Creative Common License. Created with ♥ by @robinweser and all the great contributors.