LoginSignup
7
5

More than 5 years have passed since last update.

react-overlaysを使っていてbodyの直下に置きたいコンポーネントを作る

Last updated at Posted at 2016-07-27

ReactはWebアプリの画面をコンポーネントに分割して作るスタイルを強力に推し進めてくれる。

ただ、ときどき、今の階層がどこにあるかにかかわらず、body直下に要素を置きたくなることがある。代表的なものには、モーダルダイアログの背景のように、画面全体を覆ってユーザ操作を遮断するオーバーレイがある。

こういうの↓だね。
スクリーンショット 2016-07-28 2.16.51 1.png

これを実現してくれる高レベルなコンポーネントとしてはReact-BootstrapのModalがあるが、bootstrap.cssへの依存が生じてしまうのが難点だし、見た目を変えにくいのも辛い。

そんなときには、もっと低レベルなコンポーネントであるreact-overlaysが使える。

サンプル

jsx

import Modal        from 'react-overlays/lib/Modal';

...

render: function() {
  return (
    <Modal show={true} className="modal">
      <div className="dialog">
        <h2>react-overlays</h2>
      </div>
    </Modal>
  )
}

css

.modal {
    background-color: rgba(0,0,0,.6);
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}
.modal .dialog {
    background-color: rgba(255,235,235,1)
    border-radius: 4px;
    box-shadow: 0px 0px 6px 3px rgba(255,99,99,0.46);
    margin: 30px;
    padding: 1em;
}

こんな↓感じで、bootstrap.cssに依存せず自由にデザインできる。
スクリーンショット 2016-07-28 2.30.13.png

react-overlaysのModalは、body直下にdivを追加してくれるので、画面全体を覆う要素を手軽に作れる。
showプロパティで表示/非表示が切り替えられる。

非常にシンプルだが、便利なコンポーネントだと思う。

ちなみにreact-bootstrapのModalは、react-overlaysを使って作られている。

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