modal using tailwind with dark overlay, click outside to close, toggle button, click ok to close.

PHOTO EMBED

Wed Sep 06 2023 16:03:38 GMT+0000 (Coordinated Universal Time)

Saved by @sadik #css #tailwindcss #react.js #frontend #style

import { useRef, useState } from "react";

const Modal = () => {
  const contentRef = useRef(null);
  const [isOpen, setIsOpen] = useState(false);

  const handleClickOutside = (event) => {
    if (contentRef.current && !contentRef.current.contains(event.target)) {
      console.log(`object`);
      setIsOpen(false);
    }
  };

  const toggleModal = () => {
    setIsOpen(!isOpen);
  };
  

  return (
    <div>
      <style>
        {`
/* Modal container */
.modal-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent overlay */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Modal content */
.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  max-width: 400px;
  text-align: center;
}
	`}
      </style>
      <button
        className="px-2 bg-blue-300 py-1 rounded-lg"
        onClick={toggleModal}
      >
        Toggle Modal
      </button>
      {isOpen && (
        <div
          className="modal-container border border-pink-600 select-none"
          onClick={handleClickOutside}
        >
          <div className="modal-content" ref={contentRef}>
            <h2>Click outside to close</h2>
            <p>This is a modal. Click outside to close.</p>
            <button
              className="px-3 py-1 mt-3 rounded-md bg-teal-300"
              onClick={() => setIsOpen(false)}
            >
              ok
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default Modal;
content_copyCOPY

with the help of chat gpt, a slight improvement from chatgpt is that the ref must be set to the modal-content div, not the modal-container div url: https://chat.openai.com/share/8f1f514b-9bc2-4019-ad1e-a6a5f203a87b

https://chat.openai.com/share/8f1f514b-9bc2-4019-ad1e-a6a5f203a87b