LoginSignup
0
0

More than 1 year has passed since last update.

Reactでモーダル背景固定用CustomHooks

Posted at

モーダルで背景を固定したい時のCustomHooks

CustomHook

import { useEffect, useState } from "react";

export const useScrollLock = (isLock: boolean): void => {
  const [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    if (isLock) {
      const y = window.scrollY;
      setScrollY(y);
      document.body.style.position = "fixed";
      document.body.style.top = `-${y}px`;
      document.body.style.height = "auto";
    } else {
      document.body.style.position = "";
      document.body.style.top = "";
      document.body.style.height = "";
      window.scrollTo(0, scrollY);
    }
  }, [isLock]);
};

使用例

export const Modal = (props: Props) => {
  useScrollLock(props.isOpen);

  // 省略
}
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