The previous lesson in this module covered holding state in a plain object, and this one builds on that by showing how to turn that state into markup. A render function takes data and gives you back markup. That is the whole idea, and it sounds small enough to be obvious, but the details are where render functions earn their keep. You have to decide whether a function returns a node or a string, you have to keep user data from turning into executable markup, and you have to make sure that the function only reads its own arguments. The last lesson in this module puts all of this together into a small, accessible user interface.
What makes a function a render function?
It has three properties. It takes data as arguments and returns the markup for that data. It does not read anything else, so there is no document, no globals, and no Date.now(). And it has no side effects, which means that calling it does not change the page.
That third point is the one that pays off. A pure render function can be called twice with the same data and it will produce the same result, so you can render a list of fifty items by calling the function fifty times without worrying about the order of anything. It can also be tested without a browser at all, which is something that you cannot say about code that reaches into the document.
<div id="board"></div>
<ul id="roster"></ul>
<table id="scores">
<caption>Weekly scores</caption>
<thead><tr><th>Name</th><th>Score</th></tr></thead>
<tbody></tbody>
</table>
const board = document.querySelector("#board");
function renderCard(product) {
const card = document.createElement("article");
card.className = "card";
card.dataset.sku = product.sku;
const name = document.createElement("h3");
name.textContent = product.name;
const price = document.createElement("p");
price.className = "price";
price.textContent = product.price;
card.append(name, price);
return card;
}
const products = [
{ sku: "A-1", name: "Desk lamp", price: "$24" },
{ sku: "B-2", name: "Monitor stand", price: "$41" },
];
for (const product of products) {
board.append(renderCard(product));
}
console.log(board.querySelectorAll(".card").length); // 2
console.log(board.querySelector("h3").textContent); // "Desk lamp"
Notice what the function does not do. It never touches board, and it does not even know that the board exists. The caller decides where the result goes, which means that the same renderCard function could produce a card for a sidebar, for a dialog, or for a preview pane without any change at all.
Should a render function return a node or a string of HTML?
Both of them work, and the difference is mostly about where the safety lives. A function that returns a node uses textContent for text, so any string is inserted as characters and nothing can ever be parsed as markup. You get that safety for free, without having to think about it.
A function that returns a string is more compact, and for a very large list it is faster to build one big string and parse it once than to create thousands of small elements. The cost is that you must escape every value yourself, because a plain string carries no idea of which parts are code and which parts are data.
const board = document.querySelector("#board");
function escapeHtml(value) {
return String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
const product = { sku: "A-1", name: "Desk <b>lamp</b>", price: "$24" };
const html = '<article class="card" data-sku="' + escapeHtml(product.sku) + '">'
+ '<h3>' + escapeHtml(product.name) + '</h3>'
+ '</article>';
board.innerHTML = html;
console.log(board.querySelector("h3").textContent); // "Desk <b>lamp</b>", shown as text
console.log(board.querySelector("b")); // null, nothing was parsed as markup
If you forget one escapeHtml call, then the difference between the two approaches stops being a style choice and becomes a security hole. Many teams pick the node-returning style precisely because the safe choice there is the one that needs no extra thought.
How can you avoid the createElement boilerplate?
Every render function written the long way spends most of its lines on plumbing. A small helper that takes a tag, a bag of properties, and a list of children removes that noise and leaves the interesting part, which is what the markup means, clearly visible.
function h(tag, props = {}, ...children) {
const el = document.createElement(tag);
for (const entry of Object.entries(props)) {
const key = entry[0];
const value = entry[1];
if (key === "class") {
el.className = value;
} else if (key === "dataset") {
Object.assign(el.dataset, value);
} else if (key === "text") {
el.textContent = value;
} else {
el.setAttribute(key, value);
}
}
for (const child of children) {
if (child instanceof Node) {
el.append(child);
} else {
el.append(document.createTextNode(String(child)));
}
}
return el;
}
const card = h("article", { class: "card", dataset: { sku: "C-3" } },
h("h3", { text: "Cable organiser" }),
h("p", { class: "price", text: "$9" }),
);
console.log(card.outerHTML);
Two details in that helper are worth pointing out. The text property is assigned to textContent, so text never becomes markup no matter what it contains. And any child that is not already a node is turned into a text node, which means that you can pass a plain string or a number without it being parsed.
Do not over-engineer the helper, though. An h function that supports every possible attribute, spread props, and slots quickly becomes a framework with its own bugs. Two or three files and a handful of properties is plenty.
There is one more decision to make, and it is about where the text goes. In the helper above, a text property sets textContent on the element itself. The alternative is to treat text as a child, so that h("p", "Some text") produces a paragraph with a text node inside it. Both are fine, and the child version composes better because you can pass a mix of strings and nodes in the same list.
How do you compose small render functions into a bigger one?
Because a render function returns a node rather than a string, composition is simply passing the result of one function into another as a child. There is no template language to learn and no context to keep track of, and each piece stays small enough to read on its own.
const roster = document.querySelector("#roster");
function renderBadge(text) {
const span = document.createElement("span");
span.className = "badge";
span.textContent = text;
return span;
}
function renderPerson(person) {
const row = document.createElement("li");
row.className = "person";
row.append(document.createTextNode(person.name), renderBadge(person.role));
return row;
}
roster.append(
renderPerson({ name: "Ada", role: "Engineer" }),
renderPerson({ name: "Grace", role: "Admiral" }),
);
console.log(roster.querySelectorAll(".person").length); // 2
console.log(roster.querySelector(".badge").textContent); // "Engineer"
Notice that renderBadge knows nothing about people, and renderPerson knows nothing about lists. That is the payoff of keeping render functions pure, because they can be tested on their own, reused in a different layout, and changed without hunting through all of the code that calls them.
What does a render function look like for a table?
Tables are a good test of a render function, because the shape of the markup depends on the data in ways that are easy to get wrong by hand. A renderer that takes the rows and a list of column descriptions can build the body cells without caring what the data actually means.
const table = document.querySelector("#scores");
function renderTable(rows, columns) {
const body = table.tBodies[0];
body.replaceChildren();
for (const row of rows) {
const tr = document.createElement("tr");
for (const column of columns) {
const cell = document.createElement("td");
cell.textContent = String(column.get(row));
tr.append(cell);
}
body.append(tr);
}
}
const rows = [{ name: "Ada", score: 91 }, { name: "Grace", score: 97 }];
const columns = [
{ get: function (row) { return row.name; } },
{ get: function (row) { return row.score; } },
];
renderTable(rows, columns);
console.log(table.tBodies[0].rows.length); // 2
console.log(table.tBodies[0].rows[1].cells[0].textContent); // "Grace"
The column descriptions are the interesting part. Each one knows how to pull a single value out of a row, and the renderer does not need to know whether that value is a name, a price, or a formatted date. Adding a column means adding one entry to the array instead of editing the code that builds the markup.
How can you check a render function without a whole page?
Because a render function touches nothing outside its own arguments, you can call it and look at what comes back. There is no need to build a page, attach the result to the document, or fire an event. You simply inspect the returned node directly, and that makes render functions the easiest part of a front-end codebase to test.
function renderBadge(text) {
const span = document.createElement("span");
span.className = "badge";
span.textContent = text;
return span;
}
// No page needed, just inspect the returned node.
const badge = renderBadge("<b>Engineer</b>");
console.log(badge.tagName); // "SPAN"
console.log(badge.className); // "badge"
console.log(badge.textContent); // "<b>Engineer</b>"
console.log(badge.querySelector("b")); // null, the tags stayed characters
The last line is the important assertion, because it is one line of code that proves the renderer cannot be tricked into producing markup from its input. It will still pass in a year when somebody refactors the helper. Tests like this are much harder to write against code that reaches into the document, and that is the practical argument for keeping render functions pure.
The render function reference
renderThing(data)takes data, returns a node, and changes nothing else.element.textContent = valueis the safe way to put any string into markup.element.append(child)composes one render function's result into another.h(tag, props, ...children)is a small helper that cuts the boilerplate.escapeHtml(value)is required for every value in a string-based renderer.renderTable(rows, columns)drives the markup from data using column descriptions.
Try it yourself: write a render function for a single review card that takes an object with a name, a rating, and a comment, and that returns an element. Then write a second function that renders a list of reviews and returns a <ul>. Try inserting a comment that contains <script>alert(1)</script> as the comment text and confirm that it appears as characters rather than running. Finally, rewrite the list renderer so that it returns a string instead of nodes, add an escaping function, and check that the same comment still appears as characters.