Home > other >  How to make sure document is ready before calling getElementById() in Typescript
How to make sure document is ready before calling getElementById() in Typescript

Time:02-03

I have a component that loads some HTML (converted from MD via marked library) and diplays it to the page and if a row is clicked, the document will scroll to the appropriate HTML element with the matching headerID on the page.

import { marked } from 'marked';


const [content, setContent] = React.useState('');
React.useEffect(() => {
    if (!source) {
        return;
    }
    getRequest(source)
        .then(response => {
            if (!response.ok) {
                return Promise.reject(response);
            }
            return response.text().then(faq => {
                // sets page to html
                setContent(marked(faq));
                const nearestHeader = document.getElementById(headerID);
                if (nearestHeader) {
                    // if search result is clicked, jump to result's nearest header
                    nearestHeader.scrollIntoView(true);
                    setRowClicked(false);
                }
            });
        })
        .catch(e => Dialog.error('Failed to load page.', e));
}, [source, rowClicked]);

However, when I go to test this code the 'nearestHeader' object is always null even after I verified that the headerID matches up with the existing HTML element's ID I want to navigate to. How can I make sure document is ready/loaded before attemping the getElementById call without using extra libraries?

CodePudding user response:

you can use the window.onload event to make sure the document is ready before calling getElementById() for an element that is not within the component.

 useEffect(() => {
    window.onload = function() {
      const element = document.getElementById("headerID");
    };
  }, []);

CodePudding user response:

Solved by adding another useEffect call which waits on content of page to be set first. Removed nearestHeader code from the initial useEffect() call that sets content

React.useEffect(() => {
    const nearestHeader = document.getElementById(headerID);
    if (nearestHeader) {
        nearestHeader.scrollIntoView(true);
        setRowClicked(false);
    }
}, [content]);
  • Related