0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React/Material UIのCSSでアニメーションが動かない原因(@keyframes)

Last updated at Posted at 2021-02-10

Material UIのCSSの正体

Material UIで扱うCSSの実体はJSSです。
makeStylescreateStylesを利用している場合、
記法はJSS公式ドキュメントを確認する必要があります。

ここでは記法については説明しませんのでご了承を。

CSSアニメーションが動かない場合

デベロッパーツールのConsoleでこんなwarningログが出ていませんか?

Warning: [JSS] Unknown rule @-webkit-keyframes xxxxx
Warning: [JSS] Unknown rule @keyframes xxxxx

@keyframesで設定したanimation-nameが読み取れない、というメッセージですね。
このようなログが出る原因は@keyframesの記法が間違っているからです。
実装例を見ながら確認していきましょう。

@keyframesの実装例

まずはJSS公式ドキュメントを確認

>>公式ドキュメント

const styles = {
  '@keyframes slideRight': {
    from: {opacity: 0},
    to: {opacity: 1}
  },
  targetClass: {
    animationName: '$slideRight'
  }
}

ポイント
animationNameの先頭に$を付けて呼び出す

一般的なCSSの記法と異なるのでびっくりした方もいるのではないでしょうか。
warningログが出ていた原因はこれだったのです。
では、実装に落とし込んでみましょう。

実装例

ここでは、ローディング画面でくるくる回るスピナーの実装を想定しています。
細かいCSSは省略して@keyframesに関わる部分だけを抜粋。

ローディング画面のspinnerスタイル

import React from 'react';
import { createStyles, Theme, makeStyles } from '@material-ui/core/styles';

const commonStyles = makeStyles((theme: Theme) =>
    createStyles({
        '@-webkit-keyframes spin': {
            '0%': {
                '-webkit-transform': 'rotate(0deg)',
                transform: 'rotate(0deg)',
            },
            '100%': {
                '-webkit-transform': 'rotate(360deg)',
                transform: 'rotate(360deg)',
            }
        },
        '@keyframes spin': {
            '0%': {
                '-webkit-transform': 'rotate(0deg)',
                transform: 'rotate(0deg)',
            },
            '100%': {
                '-webkit-transform': 'rotate(360deg)',
                transform: 'rotate(360deg)',
            }
        },
        spinner: {
            // 省略
            '-webkit-transform': 'translateZ(0)',
            '-ms-transform': 'translateZ(0)',
            transform: 'translateZ(0)',
            '-webkit-animation': '$spin 1.1s infinite linear',
            animation: '$spin 1.1s infinite linear',
        },

このように
animationのショートハンドを使って呼び出すことも可能です。

animation: '$spin 1.1s infinite linear',

これでアニメーションが動くようになるはずです。
参考になれば。

参考記事

JSS公式サイト

Qiita
React: Material-UI 4.0のコンポーネントへのCSS設定はwithStyles()からmakeStyles()に

0
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?