LoginSignup
0
0

More than 1 year has passed since last update.

React+Material UIにおける、ボタン押下時の@keyframesアニメーション①

Last updated at Posted at 2021-10-17

初めに

ボタン押したときにkeyframeで設定しているアニメーションを発動
そしてタイトルが長いな、、
※初回にアニメーションが走るのは何とかしたいが、、、

こんな感じのもの

ボタンを押すと、領域が拡大or縮小します

コード

import { useState } from "react";
import { Box, Button } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import clsx from "clsx";

// classオブジェクト定義
const useStyles = makeStyles(() => ({
  // 開閉共通のclass(jsx側に設定)
  commonItem: {
    backgroundColor: "#ff0000",
    width: "200px",
  },
  // 開くときのclassオブジェクト(jsx側に設定)
  openedItem: {
    animation: `$openEffect 1000ms`,
    height: "100px",
  },
  // 閉じるときのclassオブジェクト(jsx側に設定)
  closedItem: {
    animation: `$closeEffect 1000ms`,
    height: "30px",
  },
  // 開いた時の動作
  "@keyframes openEffect": {
    "0%": {
      height: "30px",
    },
    "100%": {
      height: "100px",
    },
  },
  // 閉じたときの動作
  "@keyframes closeEffect": {
    "0%": {
      height: "100px",
    },
    "100%": {
      height: "30px",
    },
  },
}));

// コンポーネント
const TestComponet = () => {
  // classオブジェクト生成
  const classes = useStyles();
  // 開閉のフラグ
  const [isOpen, setIsOpen] = useState(true);

  return (
    <>
      {/* 開閉、共通のclassをBoxに設定 */}
      <Box
        className={[
          clsx(
            classes.openedItem,
            {
              [classes.closedItem]: !isOpen,
            },
            classes.commonItem
          ),
        ]}
      >
        {/* 開閉ボタン(設定値と逆のフラグを設定) */}
        <Button onClick={() => setIsOpen(!isOpen)}>開閉</Button>
      </Box>
    </>
  );
};

export default TestComponet;

最後に

初のReact関連記事!
yarn add 関連はうまくやって下さい、、

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