Snippets Collections
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;
import {userRef,UseEffect} from "react"
function App()=>{
  const refOne = useRef(null);
  
  useEffect(() => {
    document.addEventListener("click", handleClickOutside, true);
  }, []);
  
  const handleClickOutside = (e) => {
    if (refOne.current && !refOne.current.contains(e.target)) {
      console.log("clicked outside");
    } else {
      console.log(`clicked inside div`);
    }
  };
 return(
 <div style={{width:"10rem",height:"10rem", backGround:"red"}}>
 </div>) 
}
star

Wed Sep 06 2023 16:03:38 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/share/8f1f514b-9bc2-4019-ad1e-a6a5f203a87b

#css #tailwindcss #react.js #frontend #style
star

Wed Sep 06 2023 05:41:11 GMT+0000 (Coordinated Universal Time)

#css #tailwindcss #react.js #frontend #style

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension