Preview:
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;
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter