Search code examples
reactjsnext.jsuse-effectuse-ref

Selecting a DOM element inside of a useEffect Hook


I'm trying to select an element that is inside of another element in the DOM that I selected using useRef hook.

const editorRef = useRef(null);

Inside of a useEffect hook i try to select the child element on the editorRef

useEffect(() => {
   editorRef.current.querySelector(".ql-editor").innerHTML = post.content; 
}, []);

But I get a

TypeError: "Cannot set property 'innerHTML' of null"

but when I save my code after the first refresh, it actually works and innerHTML gets populated.


Solution

  • useEffect Hook calls the function you that you passed to its dependency before the DOM creation.
    So since there is no DOM, there will be no elements to select and it causes an undefined error.

    There is another hook called useLayoutEffect that will call the function after DOM is created

     useLayoutEffect(() => {
       editorRef.current.querySelector(".ql-editor").innerHTML = post.content; 
    }, []);
    

    Read more about useLayoutEffect in Here