6
3

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 1 year has passed since last update.

Reactでモーダルコンポーネント実装

Last updated at Posted at 2020-08-03

はじめに

今回、インターン先の開発でモーダルコンポーネントを触る機会があったのでモーダルコンポーネントの理解を深めるために一からモーダルコンポーネントを実装してみました。スタイリングはstyled-componentを使用しています。

完成形

画面収録 2020-08-03 20.58.37.mov.gif

この猫の写真の部分に中に吐き出したいコンポーネントを入れていきます。
モダールという文字列をクッリクするとモーダルが開くようにしてます。

手順

  1. 必要なpropsを定義。今回は表示させたい内容を渡すchildren,モーダル開閉状態を渡すisOpen,モダールを開くトリガーを渡すonClickを定義します。
type Props = {
  children: JSX.Element; //表示させたい内容
  isOpen: boolean; //モーダル開閉状態の真偽
  onClick: Function;//モダールを開くトリガーになる関数
};

2.次にstyled-componentsを使いモーダルの開閉状態のcssでスタイル

const Div = styled.div`
  @keyframes fadeIn {
    from {
      opacity: 0; /*アニメーション開始時は不透明度0%*/
    }
    to {
      opacity: 1;  /*アニメーション終了時は不透明度100%*/
    }
  }
  display: none;
  &.fadeIn {
    display: block;
    animation: fadeIn 0.25s; /*アニメーションにかかる時間(1s=1秒)/
  }
`;

ここでは、cssの「animation」プロパティを使いフェードインを実装しています。

3.上の二つを利用し実装

コードはこんな感じ

export const Modal: React.FC<Props> = ({
  children,
  isOpen,
  onClick,
}: Props) => {
  return (
    <Div
      className={`${
        isOpen ? 'fadeIn' : ''
      } w-full h-full justify-center flex items-center fixed`}//真ならfaidInさせる
    >
      <div
        className="fixed bg-black opacity-50 w-full h-full top-0 left-0"
        onClick={() => onClick()} //モーダルの外側
      />
      <div className="bg-white w-10/12 mx-auto rounded-lg z-50 fixed top-50 left-50 -translate-x-1/2 -translate-y-1/2 transform">
        <div className="py-1 px-3">
          <div className="relative">
            <div className="absolute h-4 top-0 right-0">
             //この中にはモダールを開くトリガーになるボタンなどが入る
            </div>
          </div>
          <div className="mt-8 mb-6 mx-3 flex justify-center items-center">
            {children}//表示させたい内容
          </div>
        </div>
      </div>
    </Div>
  );
};

まとめ

今回モーダルコンポーネントを実装することでモーダルがどのような仕組みで動いているのかを理解することができました。a11yやパフォーマンスなどはあまり考慮できていないので、その辺を意識した実装も今後記事に残したいと思います。

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?