Categories
JavaScript

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *