simple-vdom

0.0.3 • Public • Published

vdom

Simple JavaScript Virtual DOM. Compatible with htm.

Codacy Badge

Install

# npm
npm i simple-vdom
# pnpm
pnpm i simple-vdom
# yarn
yarn add simple-vdom

Example

Try it yourself

To build the example, clone the repository and write this to command line:

pnpm example

It will build the example. Then, launch a server for example directory. For example:

serve -s example -p 3000

And open it in a browser.

Code

import { h, render, diff } from 'simple-vdom'
import htm from 'htm'

const html = htm.bind(h)

// Create App component with a prop "counter"
let App = (counter) => html`<p style="${{ fontSize: counter * 2 + 'px' }}">
  <span>${counter}</span>
</p>`

// Return component with passed prop
let AppWithProps = App(0)

// Mount first state of app to container
let mount = render(AppWithProps, document.getElementById('app'))

setInterval(() => {
  // Generate random number
  const newCounter = parseInt(Math.random() * 10)

  // Return new state of app with new prop
  const newApp = App(newCounter)

  // Check for changes and collect patches
  const patch = diff(AppWithProps, newApp)

  // Replace old app with new one
  AppWithProps = newApp

  // Mount patched app
  mount = patch(mount)

  // Replace element
  document.getElementById('app').firstChild.replaceWith(patch(mount))
}, 1000)

API

h

A hyperscript function that returns vnode (a plain object)

const el = h('h1', null, 'Hello')

console.log(el)

/*
{
  tag: 'h1',
  props: null,
  children: 'Hello'
}
*/

renderNode

Renders objects created by h to DOM nodes

const vnode = renderNode(html`<h1>Hello World</h1>`)

console.log(vnode)

/*
[Object HTMLElement]
*/

render

Append vnode to DOM container.

render(html`<h1>Hello World</h1>`, document.getElementById('app'))

diff

Check for differences in DOM and return patches.

const App = html`<p>Hi</p>`

const newApp = html`<p>Hello</p>`

const dom = diff(App, newApp)

render(dom, document.getElementById('app'))

License

MIT © v1rtl

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 0.0.3
    1
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 0.0.3
    1
  • 0.0.2
    0
  • 0.0.1
    0

Package Sidebar

Install

npm i simple-vdom

Weekly Downloads

1

Version

0.0.3

License

MIT

Unpacked Size

7.48 kB

Total Files

5

Last publish

Collaborators

  • dropthebeatbro