# Raw HTML

> innerHTML sets an element's content to a string of markup. Every framework renders it as written, and the compiler warns that the markup isn't escaped.

Raw HTML lets a component show markup it receives as a string, like the body of an article from a CMS, a Markdown renderer's output or a highlighted code sample. In Unframework you set it with `innerHTML`, the DOM's own name for it, and every framework renders the markup as HTML. Think of a blog post whose paragraphs show up as literal `<p>` tags, a Vue port that uses `v-html` and a React port that forgets `__html`, or an Angular app that quietly strips the `id` your table of contents links to.

This page walks you through setting markup on an element, and what the compiler checks. We'll look at:

- **Markup as content:** `innerHTML`, and what each framework receives.
- **The warning:** why the compiler reports every use.
- **Where it can go:** the elements that take markup, and the values it takes.

## Markup as content

Give an element `innerHTML`, and its content is the markup the string holds. The value can be a prop, any other expression whose value is a string, or a static string:

<!-- prettier-ignore -->
```tsx [Article.uf.tsx]
export interface ArticleProps {
  title: string;
  body: string;
}

export default function Article({ title, body }: ArticleProps) {
  return (
    <article class="article">
      <h2>{title}</h2>
      <div class="body" innerHTML={body} />
      <footer innerHTML="<small>Filed under <em>News</em></small>" />
    </article>
  );
}
```

Each framework sets the markup its own way: React and Qwik through `dangerouslySetInnerHTML`, Vue through `v-html`, Svelte through `{@html}`, Solid through `innerHTML` and Astro through `set:html`:

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [Article.tsx]
import type { CSSProperties } from "react";

export interface ArticleProps {
  title: string;
  body: string;
}

export interface ArticleAttributes {
  className?: string;
  style?: CSSProperties;
}

export default function Article({
  title,
  body,
  className,
  style,
  ...attributes
}: ArticleProps & ArticleAttributes) {
  return (
    <article className={cx("article", className)} style={style} {...scopeAttributes(attributes)}>
      <h2>{title}</h2>
      <div className="body" dangerouslySetInnerHTML={{ __html: body }} />
      <footer dangerouslySetInnerHTML={{ __html: "<small>Filed under <em>News</em></small>" }} />
    </article>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#vue

<!-- prettier-ignore -->
```vue [Article.vue]
<script setup lang="ts">
export interface ArticleProps {
  title: string;
  body: string;
}

const { title, body } = defineProps<ArticleProps>();
</script>

<template>
  <article class="article">
    <h2>{{ title }}</h2>
    <div class="body" v-html="body"></div>
    <footer v-html="'<small>Filed under <em>News</em></small>'"></footer>
  </article>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [Article.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts" module>
  export interface ArticleProps {
    title: string;
    body: string;
  }
</script>

<script lang="ts">
  import type { ClassValue } from "svelte/elements";

  type Props = ArticleProps & { class?: ClassValue; style?: string };

  let { title, body, class: className, style, ...attributes }: Props = $props();

  /** The scope attributes of the styled parents that render this component, for its root. */
  function scopeAttributes(props: object): Record<string, ""> {
    const scope: Record<string, ""> = {};
    for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
    return scope;
  }
</script>

<article class={["article", className]} {style} {...scopeAttributes(attributes)}>
  <h2>{title}</h2
  ><div class="body">{@html body}</div
  ><footer>{@html "<small>Filed under <em>News</em></small>"}</footer>
</article>
```

#angular

<!-- prettier-ignore -->
```ts [article.ts]
import {
  Component,
  Directive,
  ElementRef,
  type OnInit,
  Pipe,
  type PipeTransform,
  Renderer2,
  inject,
  input,
} from "@angular/core";
import { DomSanitizer, type SafeHtml } from "@angular/platform-browser";

export interface ArticleProps {
  title: string;
  body: string;
}

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** Marks markup trusted, so that `[innerHTML]` renders it as written. */
@Pipe({ name: "trustedHtml" })
class TrustedHtmlPipe implements PipeTransform {
  private readonly sanitizer = inject(DomSanitizer);

  transform(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

@Component({
  selector: "uf-article",
  imports: [ScopeAttributes, TrustedHtmlPipe],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let title = this.title();
    @let body = this.body();
    <article class="article" [class]="this.class()" [style]="this.style()" [ufScope]="this.host">
      <h2>{{ title }}</h2>
      <div class="body" [innerHTML]="body | trustedHtml"></div>
      <footer
        [innerHTML]="'\\u003csmall\\u003eFiled under \\u003cem\\u003eNews\\u003c/em\\u003e\\u003c/small\\u003e' | trustedHtml"
      ></footer>
    </article>
  `,
})
export default class Article {
  readonly title = input.required<string>();
  readonly body = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [Article.tsx]
import type { JSX } from "solid-js";

export interface ArticleProps {
  title: string;
  body: string;
}

export default function Article(
  props: ArticleProps & { class?: string; style?: JSX.CSSProperties },
) {
  return (
    <article
      class={props.class ? `article ${props.class}` : "article"}
      style={props.style}
      {...scopeAttributes(props)}
    >
      <h2>{props.title}</h2>
      <div class="body" innerHTML={props.body} />
      <footer innerHTML={"<small>Filed under <em>News</em></small>"} />
    </article>
  );
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
```

#qwik

<!-- prettier-ignore -->
```tsx [Article.tsx]
import { type CSSProperties, type ClassList, component$ } from "@qwik.dev/core";

export interface ArticleProps {
  title: string;
  body: string;
}

export default component$<ArticleProps & { class?: ClassList; style?: CSSProperties }>(
  ({ title, body, class: className, style, ...attributes }) => {
    return (
      <article class={["article", className]} {...scopeAttributes(attributes)} style={style}>
        <h2>{title}</h2>
        <div class="body" dangerouslySetInnerHTML={body || undefined} />
        <footer dangerouslySetInnerHTML={"<small>Filed under <em>News</em></small>"} />
      </article>
    );
  },
);

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#astro

<!-- prettier-ignore -->
```astro [Article.astro]
---
export interface ArticleProps {
  title: string;
  body: string;
}

interface Props extends ArticleProps {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { title, body, class: className, style } = Astro.props;

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
---

<article class:list={["article", className]} style={style} {...scopeAttributes(Astro.props)}>
  <h2>{title}</h2>
  <div class="body" set:html={body}></div>
  <footer set:html={"<small>Filed under <em>News</em></small>"}></footer>
</article>
```

::

Angular sanitises a bound `innerHTML`: it would drop the `id`, the `data-*` attribute and the `style` attribute of this article's markup, and its form controls and SVG. So its output passes the markup through a small pipe, `TrustedHtmlPipe`, which marks it trusted, and Angular renders it as written too. Qwik's server writes an empty string as an attribute, so its output passes `body || undefined`, which renders an empty element.

When the string changes, the element's content is replaced, after hydration too. A list's element can take its item's markup, `<li key={entry.id} innerHTML={entry.html} />`.

## The warning

The compiler doesn't escape or sanitise the markup on any framework, so markup from a user or another site can run script in your page. The compiler reports every `innerHTML` as a warning, [UF3051](/docs/reference/diagnostics#UF3051), at the attribute. The component still compiles.

Render only markup you trust, like your own content, or markup a sanitiser such as DOMPurify has cleaned before it reaches the component. Text is safer as children, `<p>{comment}</p>`, which every framework escapes.

## Where it can go

The markup replaces the element's content, so the element has no children of its own. A void element holds no content, and the content of a `<textarea>` is its text. The compiler reports each of them, [UF3052](/docs/reference/diagnostics#UF3052):

<!-- prettier-ignore -->
```tsx [Notice.uf.tsx]
// UF3052 raw-html-content: `innerHTML` replaces the content of an element that has children too,
// and a void element or a text-only element holds no markup for it to set.
export interface NoticeProps {
  message: string;
}

export default function Notice({ message }: NoticeProps) {
  return (
    <section class="notice">
      <p innerHTML={message}>Loading…</p>
      <hr innerHTML={message} />
      <textarea innerHTML={message} />
    </section>
  );
}
```

<!-- prettier-ignore -->
```text
error[UF3052]: `innerHTML` replaces the content of this <p>, which has children too.
  --> diagnostics/raw-html-content/Notice.uf.tsx:10:10
   |
10 |       <p innerHTML={message}>Loading…</p>
   |          ^^^^^^^^^
   |
   = help: Remove the children, or put the markup in an element of its own beside them: `<div innerHTML={markup} />`.
   = see: https://unframework.dev/diagnostics/UF3052

error[UF3052]: <hr> is a void element: it holds no content for `innerHTML` to set.
  --> diagnostics/raw-html-content/Notice.uf.tsx:11:11
   |
11 |       <hr innerHTML={message} />
   |           ^^^^^^^^^
   |
   = help: Put the markup in an element that holds content, such as a <div> or a <span>.
   = see: https://unframework.dev/diagnostics/UF3052

error[UF3052]: The content of <textarea> is text, which the targets set apart from `innerHTML`.
  --> diagnostics/raw-html-content/Notice.uf.tsx:12:17
   |
12 |       <textarea innerHTML={message} />
   |                 ^^^^^^^^^
   |
   = help: A <textarea>'s text is its value: bind it with `v-model`.
   = see: https://unframework.dev/diagnostics/UF3052
```

The value is a string. A value that may be `undefined` or `null` is rejected, [UF3018](/docs/reference/diagnostics#UF3018), since the frameworks write those differently: give it a fallback, `innerHTML={body ?? ""}`. A component renders its own content, so `innerHTML` on a component is rejected as a prop it doesn't declare. Pass the markup as a prop, and set it on one of the component's elements.

A few forms aren't supported yet, [UF1002](/docs/reference/diagnostics#UF1002):

- A static string that holds `\`, `&` or a line break. JSX reads it as written, where each framework's template would read its escapes, so write it as an expression, `innerHTML={"Tom &amp; Jerry"}`.
- `innerHTML` on an SVG element, whose markup the frameworks parse as HTML or as SVG.
- `innerHTML` on `<component is>`, which Vue writes as a component. Write each tag in a conditional instead, `nested ? <h3 innerHTML={title} /> : <h2 innerHTML={title} />`.

The markup must be content its element permits. The server's HTML is parsed as part of the page, and the browser's markup inside the element, so a `<div>` inside a `<p>` closes the `<p>` on the server and stays inside it in the browser. The compiler can't see markup that only arrives at run time, so that one is yours to keep.

The decision behind this page is [ADR-0097](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0097-raw-html-through-innerhtml.md). The rule is on [the semantics page](/docs/reference/semantics#raw-html).
