Skip to main content

How re-rendering with HTMX works

In goal 1, our server sent back an empty response. HTMX had nothing to put on the page, so the page didn’t change.

This time, we want the page to change. The plan is:

  1. The user clicks a checkbox.
  2. HTMX sends a POST request to the server.
  3. The server saves the change, then renders the todo item’s partial and sends back the HTML.
  4. HTMX takes that HTML and swaps it into the page, in place of the old todo item.

The server sends back HTML

This is the big idea behind HTMX: the server sends back HTML, not data.

Two rows. The top row, labelled Old school, shows a Browser box holding a Page that is redrawn from scratch. An arrow labelled request goes from the Page to a Server box that renders the whole page, and an arrow labelled a whole HTML page comes back to the Page. The bottom row, labelled With HTMX, shows a Browser box holding a Page, with a Todo item box inside the Page marked swapped in. An arrow labelled request goes from the Page to a Server box that renders just the partial, and an arrow labelled just the todo item's HTML comes back to the Todo item only.
Figure 1: Old-school pages get a whole new page back for every change. With HTMX, the server sends back only the part that changed, and only that part is redrawn.

Our todo item already has its own small template: todo/partials/todo_item.html. The home page uses it to render every item in the list. Now our toggle view can use the same template to render just one item.

That means the logic for how a todo item looks lives in one place. If the item is done, the template crosses it out. We don’t have to repeat that logic in JavaScript.

HTMX puts the HTML on the page

We need to tell HTMX two things:

  • Where the HTML should go. We use hx-target for this.
  • How it should go there. We use hx-swap for this.

Where: hx-target

By default, HTMX puts the response into the element that made the request. For us, that’s the checkbox. That’s not what we want. We want to replace the whole todo item.

So we give each todo item a unique id, and point hx-target at it:

<div id="todo-item-3">
    <input type="checkbox" hx-post="/todo/3/toggle/" hx-target="#todo-item-3" ...>
    ...
</div>

#todo-item-3 is a CSS selector. It means “the element with the id todo-item-3”.

How: hx-swap

By default, HTMX uses innerHTML. That replaces the contents of the target, but keeps the target itself.

Our partial renders the whole todo item, including its outer <div>. If we used innerHTML, we’d end up with a todo item <div> inside another todo item <div>.

So we use hx-swap="outerHTML". That replaces the whole target element with the response.

<input type="checkbox"
       hx-post="/todo/3/toggle/"
       hx-target="#todo-item-3"
       hx-swap="outerHTML">

Learn more