Update the DOM Easily with the Re:dom Library — Component Updates

John Au-Yeung
3 min readJan 12, 2021
Photo by Blaz Erzetic on Unsplash

We can update the DOM with the Re:dom library in a way easier than plain JavaScript.

In this article, we’ll look at how to use the library to diff the DOM and patch it.

Diffing

Re:dom will do the diffing and patching manually.

For example, we can write:

import { el, mount } from "redom";class Image {
constructor() {
this.el = el("img");
this.data = {};
}
update(data) {
const { url } = data;
if (url !== this.data.url) {
this.el.src = url;
}
this.data = data;
}
}
const image = new Image();
image.update({ url: "https://picsum.photos/id/237/200/300" });
image.update({ url: "https://picsum.photos/id/238/200/300" });
mount(document.body, image);

Then the 2nd image URL will be the final URL that’s set as the src of the img element.

Lists

We can create lists with an li element an array of items:

import { el, list, mount } from "redom";class Li {
constructor() {
this.el = el("li");
}
update(data) {
this.el.textContent = `Item ${data}`;
}
}
const ul = list("ul", Li);mount(document.body, ul);ul.update([1, 2, 3]);
ul.update([2, 3, 4]);

We create an Li component that has the li element.

We just set the text content to an array of items and it’ll automatically be rendered into multiple li elements each with the entry.

Also, we can set the styles and content simultaneously:

import { el, list, mount } from "redom";class Li {
constructor() {
this.el = el("li");
}
update(data, index, items, context) {
this.el.style.color = context.colors.accent;
this.el.textContent = `[${index}] - ${data}`;
}
}
const ul = list("ul", Li);mount(document.body, ul);ul.update([1, 2, 3], { colors: { accent: "green" } });
John Au-Yeung