LoginSignup
4
2

More than 3 years have passed since last update.

【StyledComponent + CSSアニメーション】keyframesに引数をつける

Posted at

StyledComponentを使ってCSSアニメーションを作る時に使うkeyframesに引数を渡して動的にアニメーションを調整する方法を、忘備録として。

結論

こんな感じ。

keyframes
import { keyframes } from 'styled-components'

export const zoomInToAnyScale = (num: number) =>
  keyframes`
    from { transform: scale(0) }
    to { transform: scale(${num}) }
  `
使い方

const StyledDiv = styled.div`
  animation: ${zoomInToAnyScale(3)} 0.3s ease 0.5s forwards;
`

const ZoomInDiv = styled.div<{ scale: nuber }>`
  animation: ${({scale}) => zoomInToAnyScale(scale) } 0.3s ease 0.5s forwards;
`

環境

一応、環境はこんな感じ。

package version
React 16.13.0
StyledComponents 5.0.1
TypeScript 3.8.3

解説

(解説というほどのものでもないけど)
StyledComponentsで宣言するkeyframesは元はただの関数です。引数にとるのはTemplateStringsArray | CSSKeyframesとなっていますが、要はCSSが書かれた文字列orオブジェクトなので、こんな書き方もできます。

keyframes
import { keyframes } from 'styled-components'

export const zoomInToAnyScale = (num: number) => {
  return keyframes({
    from: { transform: `scale(0)` },
    to: { transform: `scale(${num})` }
  })

つまりは、テンプレートリテラルなどに埋めてそのまま引数として渡せばいいだけ。
ちなみにstyled.divなどはただの関数もうちょっと複雑になってるようです。

終わりに

最近CSSアニメーションに夢中になって、いろいろな作品を見て「すげええええ」って言いながら勉強しています。
いや、本当にすごいんですよ。CSSアニメーターの方全員尊敬してます。神。

StyledComponents自体の記事は多いのですが、keyframesはあまり見かけなかったので書いてみました。
実務とかだと、ただのCSSアニメーションは扱いづらいのかもしれないですね。

トリガーで発火させるようなアニメーションは、JS側で管理しやすいreact-springとかの方が良さそうです。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2