Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render raw HTML in Preact without using Preact Markup?

Preact Markup is 8.5kb, which is half the size of Preact. Is there a way to render raw HTML without having to parse it?

One way I can think of is to render a placeholder and then replace the placeholder in componentDidMount or componentDidUpdate using innerHTML, but is there a less hacky way?

like image 317
Leo Jiang Avatar asked Jul 30 '19 05:07

Leo Jiang


1 Answers

As @pmkro mentioned in a comment, you can use dangerouslySetInnerHTML to render raw html strings.

import { h, render } from "preact";

const vnode = <div dangerouslySetInnerHTML={{
  __html: "<span>foobar</span>"
}} />

render(vnode, document.getElementById("app"));
// renders <div><span>foobar</span></div>

A fair bit of warning: You need to make absolutely sure the string that ends up in dangerouslySetInnerHTML is properly escaped. Otherwise you open yourself (and your users) up to XSS injection attacks. Hence the name dangerouslySetInnerHTML.

Disclaimer: I work on Preact.

like image 117
marvinhagemeister Avatar answered Oct 24 '22 05:10

marvinhagemeister