javascriptqwikqwikjs

How to use document in qwik. Getting document of undefined


How to access document in Qwik js. Getting document of undefined when trying to use document.getElementBtId in a component$


Solution

  • You can access to the document object only in browser client side.

    You have to use it in a useVisibleTask function which is called when document becomes visible in browser.

    export const ExampleComponent = component$(() => {
    
      useVisibleTask$(() => {
    
        // Only runs in the client
        const element = document.getElementById("your-id") 
    
      });
    
      return <div id="your-id">Example component</div>;
    });