Member-only story
Update the DOM Easily with the Re:dom Library — Component Updates
3 min readJan 12, 2021
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}`;
}
}