DEV Community

Discussion on: Virtual DOM in react

Collapse
 
itachiuchiha profile image
Itachi Uchiha

I think we can write a simple virtual dom function like that. This isn't best but it should work :P

const domSource = [
    {
        tagName: 'div',
        className: ''
    },
    {
        tagName: 'p',
        children: [
            {
                tagName: 'span'
            }
        ]
    }
]


function virtualDom(element, domSource) {



    domSource.forEach(elData => {

        const { tagName } = elData

        const newElement = document.createElement(tagName)

        element.appendChild(newElement);

        const hasChild = elData.children && elData.children.length;

        if(hasChild) virtualDom(newElement, elData.children)
    })

}

virtualDom(document.querySelector("#app"), domSource)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aasthapandey profile image
Aastha Pandey

Hey! Itachi uchiha
Have you tried to exceute it?
😃

Collapse
 
itachiuchiha profile image
Itachi Uchiha

I didn't. But I'm sure it will work for the first time.

When you run it secondly, probably it will create duplicate elements.