Detect Render

Advanced and fine rendering techniques

Introduction

Many times, we need to use third party library like anime.js and so on to create effects that are beyond the scope of WebLabs, and we need to get the reference to the component.

We can use document.getElementById() to get the component, but it can bring in certain errors related to timing; sometimes the selection function might occur before the component is registered to the real DOM tree, and to encounter this error, we need to get the component's reference before it was attached.

Solution - ref & subscriptions

We have a .ref() method that stores the component itself to a state after it was created. Since WebLabs component encapsulates real HTML Components, we can absolutely use the reference to use with third party library.

We can then subscribe to that specific state to indicate the storing of the element to the state; and then we can use the value in the callback function to attach third party functions to it.

Here is an example:

import { render, State } from '@weblabsjs/core'

function App() {
    const element = State() //initially undefined
    
    element.subscribe("set:after", (value) => {
    
        //this function will be called iff the element was registered
        //now you can use the value to do some stuff
        console.log( value.coreElement ) //prints the real element.    
        
    })
    
    return div(
        p("Hello world")
    ).ref( element ) //store this component to the element state
}

Now you can use the value and extract the actuall HTML through the .coreElement member. This allows you to get a real component of the DOM without searching for it; making it efficient, fast and error-free as well.

Last updated

Was this helpful?