Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable scrolling when there's a modal using nextjs tailwind?

I currently have this code set up but I don't think this is the correct one to use as it gives me "document is not defined".


export default function Modal() {
  const [modal, setModal] = useState(false);

  const toggleModal = () => {
    setModal(!modal);
  };

//   BELOW IS THE ERROR

  if (modal) {
    document.body.classList.add('active-modal');
  } else {
    document.body.classList.remove('active-modal');
  }
like image 575
Amr Ibn Il'As Avatar asked Sep 11 '25 08:09

Amr Ibn Il'As


1 Answers

I didn't test the result but try to write the if statement inside useEffect() hook. I think initially the document object is unknown to nextJs same goes for the global window object!

For side-effects always try to use useEffect() hook. useEffect() runs after the component is mounted on the DOM.

like image 70
lAbYriNth Avatar answered Sep 13 '25 06:09

lAbYriNth