๐ŸŒƒ ๋ชจ๋‹ฌ

๋ฐ•์ƒ์€ยท2022๋…„ 5์›” 1์ผ
0

โœ๏ธ blelog โœ๏ธ

๋ชฉ๋ก ๋ณด๊ธฐ
6/13

๐Ÿ˜ธ ๋ชจ๋‹ฌ ์‚ฌ์šฉ ๋ฐฉ๋ฒ• ๋ฐ ์˜ˆ์‹œ

ํด๋ฆญ ์‹œ ๋‹ซํžˆ๋Š” ๋ชจ๋‹ฌ ์ œ์ž‘

  • useModal ํ›…
import {
  Dispatch,
  MutableRefObject,
  SetStateAction,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";

const useModal = (): [
  MutableRefObject<HTMLElement | null>,
  boolean,
  Dispatch<SetStateAction<boolean>>
] => {
  const modalRef = useRef<null | HTMLElement>(null);
  const [isOpen, setIsOpen] = useState(false);

  // 2022/05/01 - ํด๋ฆญ ์‹œ ๋ชจ๋‹ฌ ๋‹ซ๊ธฐ ์ด๋ฒคํŠธ - by 1-blue
  const handleCloseModal = useCallback(() => {
    if (isOpen) setIsOpen(false);
  }, [isOpen]);

  // 2022/05/01 - ๋ชจ๋‹ฌ ๋‹ซ๊ธฐ ์ด๋ฒคํŠธ ๋“ฑ๋ก - by 1-blue
  useEffect(() => {
    setTimeout(() => window.addEventListener("click", handleCloseModal), 0);
    return () => window.removeEventListener("click", handleCloseModal);
  }, [handleCloseModal]);

  return [modalRef, isOpen, setIsOpen];
};

export default useModal;
  • Modal ์ปดํฌ๋„ŒํŠธ
import { forwardRef, useEffect } from "react";

// util
import { combineClassNames } from "@src/libs/util";

type Props = {
  children: React.ReactChild;
  className?: string;
  noScroll?: boolean;
  primary?: boolean;
};

// eslint-disable-next-line react/display-name
const Modal = forwardRef<HTMLElement, Props>(
  ({ children, className, noScroll, primary }, ref) => {
    // 2022/05/01 - ๋ชจ๋‹ฌ์ฐฝ open ์‹œ ์Šคํฌ๋กค ๊ธˆ์ง€ - by 1-blue
    useEffect(() => {
      if (!noScroll) return;
      document.body.style.overflow = "hidden";

      return () => {
        document.body.style.overflow = "auto";
      };
    }, [noScroll]);

    return (
      <aside
        className={combineClassNames(
          "z-10",
          primary
            ? "fixed -top-4 left-0 bottom-0 right-0 z-10 bg-black/80 flex justify-center items-center"
            : "",
          className ? className : ""
        )}
        ref={ref}
      >
        {children}
      </aside>
    );
  }
);

export default Modal;
  • ์‚ฌ์šฉ ์˜ˆ์‹œ
// 2022/05/01 - ๊ฒŒ์‹œ๊ธ€ ์‚ญ์ œ ๋ชจ๋‹ฌ - by 1-blue
const [modalRef, isOpen, setIsOpen] = useModal();

// jsx
{isOpen && (
  <Modal ref={modalRef} noScroll primary>
    <form className="flex flex-col bg-zinc-900 p-8 rounded-md space-y-4 w-[400px]">
      <span className="font-bold text-2xl">ํฌ์ŠคํŠธ ์‚ญ์ œ</span>
      <span>์ •๋ง ํฌ์ŠคํŠธ๋ฅผ ์‚ญ์ œํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?</span>
      <div />
      <div className="text-right space-x-2">
        <button
          type="button"
          className="px-6 py-2 bg-indigo-400 rounded-md hover:bg-indigo-500"
        >
          ์ทจ์†Œ
        </button>
        <button
          type="button"
          className="px-6 py-2 bg-indigo-400 rounded-md hover:bg-indigo-500"
          onClick={() => removePost({})}
        >
          ํ™•์ธ
        </button>
      </div>
    </form>
  </Modal>
)}

๐Ÿ‘‡ ์ฐธ๊ณ ํ•œ ์‚ฌ์ดํŠธ

๋ฆฌ์•กํŠธ ๊ณต์‹๋ฌธ์„œ - forwardRef

0๊ฐœ์˜ ๋Œ“๊ธ€