Home > Blockchain >  Why can't a getElementById method find an element when imported inside functional component?
Why can't a getElementById method find an element when imported inside functional component?

Time:12-16

I want to use this cool scroll effect in one of my pages.The functional component has the same exact HTML as in the codepen. The script is in a separate file that is imported inside the component file. The problem is this line doesn't work

var well = document.getElementById('well');

I tried to import the JS-file into a variable and the call it in a useEffect hook just to make sure that hte script is run after the DOM is rendered. But it still doesn't work. What do I do to make the script work in my component?

CodePudding user response:

Did you try importing the script like this ?

useEffect(() => {
    const script = document.createElement('script');
    script.src = "source of the js file";
    script.async = false;
    document.body.appendChild(script);
    return () => {
        document.body.removeChild(script);
      }
  }, []);
  • Related