Cannot read properties of null (reading 'classList') in react

Viewed 661

I have tried many ways to add a class to a div:

const modal = useRef(null);
modal.current.classList.add("modalShow");

const element = document.getElementById("modal");
element.classList.add("modalShow")

but I always get some error like this Cannot read properties of null (reading 'classList') . how can I fix it?

this is my live code:

Live code

import { useRef } from "react";
export default function Modal() {
  const modal = useRef(null);
  modal.current.classList.add("modalShow");
  /*const element = document.getElementById("modal");
  element.classList.add("modalShow");*/
  return <div id="modal" ref={modal} className="modalContainer "></div>;
}
3 Answers

Because you are trying to set the class to an element before it is rendered and attached to the ref.

Try this:

useEffect(()=>{
   modal.current.classList.add("modalShow");
},[]);

This will make sure the element is rendered and modal.current refers to that element, not null.

At the first renders cycles probably the modal is null:


if (modal.current) {
  modal.current.classList.add("modalShow");
}

Just do optional chaining to prevent this error:

modal.current?.classList?.add("modalShow");
Related