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 runs after the browser repaint.
    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 before the render

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

    Read more about useLayoutEffect in Here