Update the DOM Easily with the Re:dom Library — Placeholders and Routes

Image for post
Image for post
Photo by Johan Mouchet 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.

Place

We can create or destroy a component or element and reserve its place with the place method.

For example, we can write:

import { place, mount, el } from "redom";class Top {
constructor() {
this.el = el("p", "top");
}
}
class Menu {
constructor() {
this.el = el("div", "menu");
}
update(visible, data) {
if (visible) {
this.el.textContent = data;
}
}
}
class Content {
constructor() {
this.el = el("div", "content");
}
}
class App {
constructor() {
const app = el(
".app",
(this.top = new Top()),
(this.menu = place(Menu)),
(this.content = new Content())
);
this.menu.update(true, "foo");
this.menu.update(true, "bar");
this.menu.update(false);
return app;
}
}
mount(document.body, new App());

We call the place function to reserve place for the menu.

Router

Re:dom comes with a router.

We can use it by using the router function:

import { el, router, mount } from "redom";class Home {
constructor() {
this.el = el("h1");
}
update(data) {
this.el.textContent = `Hello ${data}`;
}
}
class About {
constructor() {
this.el = el("about");
}
update(data) {
this.el.textContent = `About ${data}`;
}
}
class Contact {
constructor() {
this.el = el("contact");
}
update(data) {
this.el.textContent = `Contact ${data}`;
}
}
const app = router(".app", {
home: Home,
about: About,
contact: Contact
});
mount(document.body, app);const data = "world";app.update("home", data);
app.update("about", data);
app.update("contact", data);

We create the component classes and then pass them all to the object we pass into router .

The first argument is the selector for the app.

The app.update method lets us change the route.

Conclusion

We can add routes and call place to add placeholders for components.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store