HTML API
The HTML API provides low-level functions for HTML string creation and manipulation.
Core Functions
html Template Literal
Safe HTML string creation with automatic escaping:
1import { html } from "@reface/recast";
2
3// Basic static HTML
4html`<div>Hello World</div>`;
5
6// With interpolation
7const name = "John";
8html`<div>Hello ${name}!</div>`;
9
10// Safe by default
11const unsafe = "<script>alert('xss')</script>";
12html`<div>${unsafe}</div>`;
13// <div><script>alert('xss')</script></div>
css Template Literal
Direct CSS string creation:
1import { css } from "@reface/recast";
2
3const style = css/*css*/ `
4 ​& {
5 ​ ​color: red;
6 ​}
7`;
8
9// Get root class name
10style.rootClass; // "s1a"
11
12// Get CSS styles string
13style.styles; // ".s1a { color: red; }"
14
15// Get style tag
16style.styleTag; // "<style>.s1a { color: red; }</style>"
17
18// Use with html
19html`<div class="${style.rootClass}">Content ${style.styleTag}</div>`;
20// <div class="s1a">Content <style>.s1a { color: red; }</style></div>
Function Components
Simple functions that return HTML strings:
1type ButtonProps = {
2 ​variant: string;
3};
4
5const Button = (props: ButtonProps, children: Children) => {
6 ​return html`<button class="btn ${props.variant}">${children}</button>`;
7};
8
9// Use directly
10Button({ variant: "primary" }, "Click me");
Helper Functions
attrs
Build HTML attributes string:
1import { attrs } from "@reface/recast";
2
3attrs({
4 ​class: "btn primary",
5 ​"data-id": "123",
6 ​disabled: true,
7});
8// class="btn primary" data-id="123" disabled
classes
Combine class names:
1import { classes } from "@reface/recast";
2
3classes(
4 ​"btn",
5 ​{
6 ​ ​primary: true,
7 ​ ​disabled: false,
8 ​},
9 ​["large", "rounded"]
10);
11// "btn primary large rounded"
styles
Create style string:
1import { styles } from "@reface/recast";
2
3styles({
4 ​color: "red",
5 ​fontSize: "14px",
6 ​marginTop: "10px",
7});
8// "color: red; font-size: 14px; margin-top: 10px"
Best Practices
Use html`` for Safe String Creation
1// ✓ Good - automatic escaping2html`<div>${userInput}</div>`;Use Simple Functions for Reusable Logic
1// ✓ Good - simple and type-safe2const Card = (props: CardProps, children: string) => {3 ​return html` <div class="card">${children}</div> `;4};Use Helpers for Complex Attributes
1// ✓ Good - clean and maintainable2html`<div3 ​${attrs({4 ​ ​class: classes("card", { active: isActive }),5 ​ ​style: styles({ color: theme.color }),6 ​})}7>8 ​${content}9</div>`;
See Also
JSX - High-level component syntax
Template - Higher-level template syntax
Components - Component-based architecture
Styling - CSS-in-JS solution
Render - how to render to HTML