Avoid use of dangerouslySetInnerHTML with this lightweight (2KB) function.

Overview

preact-parser

When dealing with HTML strings in Preact, our only real option is to use dangerouslySetInnerHTML. This is fine(-ish) if you 100% trust the contents of that HTML, but regardless, it opens up potential vectors for attack, problems and bugs. Ideally, we'd be able to sanitise, and convert this HTML into VDom nodes that can be natively rendered in the same manner as defined JSX or h() calls.

This lightweight package (2KB GZipped) accepts an HTML string (doesn't have to contain HTML, can be text), parses it, and returns a tree of VDom nodes ready to render by Preact. It can work both on the client (Dom Parser) and the server, so is ideal for isomorphic applications.

It automatically strips tags, so you no longer have to worry about someone "accidentally" adding an alert('Hello') in your CMS / API of choice.

Getting Started

Install with Yarn:

$ yarn add preact-parser

Install with NPM:

$ npm i preact-parser

Using parse()

preact-parser exports a single function, parse(), that accepts a string of HTML or text, and can be used directly within your component trees. As mentioned above, in the browser it makes use of the native DOM parser, and on the server uses a tiny, efficient string parser.

For example:

{parse(htmlApiResponse)}; }">
import { parse } from 'preact-parser';

/*[...]*/

const htmlApiResponse = `
   

Contrary to popular belief, Lorem Ipsum is not simply random text.

There are many variations of passages of Lorem Ipsum available

`; /*[...]*/ function BlogContent() { return <article class="content">{parse(htmlApiResponse)}</article>; }

When rendered, the above will output:

<p>Contrary to popular belief, Lorem Ipsum is not simply random text.p>
<p>There are many variations of passages of Lorem Ipsum availablep>

Acknowledgement

The server side HTML string parser in this package takes inspiration from the fantastically fast node-html-parser. That package provides a full DOM representation, including methods, which was overkill for this. In order to keep the size of preact-parser to a minimum, we've made use of the excellent parsing function found there.

You might also like...

A ~2kb hotkeys library for solid that adds only 2 event listeners.

A ~2kb hotkeys library for solid that adds only 2 event listeners.

Solid Hotkeys - Cmd+S+H Solid Hotkeys is the easiest way to add hotkeys to your application. Built for and with Solid. Motivation You gotta have hotke

Aug 1, 2022

🦾 Tiny 2kb Markdown parser written, almost as fast and smart as Tony Stark

Starkdown 🦾 Starkdown is a Tiny 2kb Markdown parser written, almost as fast and smart as Tony Stark. npm i starkdown Motivation It is a continuation

Sep 22, 2022

A lightweight function that executes callback when we see specific DOM elements.

did-i-see A lightweight function that executes callback when we see specific DOM elements. Built with IntersectionObserver. 🔴 Demo: https://did-i-see

Oct 18, 2022

EggyJS is a Javascript micro Library for simple, lightweight toast popups focused on being dependency-less, lightweight, quick and efficient.

EggyJS EggyJS is a Javascript micro Library for simple, lightweight toast popups. The goal of this library was to create something that meets the foll

Jan 8, 2023

⚖️ Limit an async function's concurrency with ease!

limit-concur Limit an async function's concurrency with ease! Install $ npm i limit-concur Usage import got from 'got' import limitConcur from 'limit-

Apr 8, 2022

An adapter where you can define which function to run

Switch Functions An adapter where you can define which function to run Installation This is a Node.js module available through the npm registry. Befor

Jun 17, 2022

This is an VanillaJS SPA example with function based rendering.

This is an VanillaJS SPA example with function based rendering.

Function-Based-Rendering This is an VanillaJS SPA example with function based rendering. Here's how to create Views by function composition and how to

Oct 16, 2021

This simple project, show how work with async Fetch, function component and class component

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Feb 17, 2022

Aergo Timer Service schedule smart contract function calls

Aergo Timer Service ⏰ Create timers to call functions on your smart contracts Schedule calls based on time interval or on specific date-times For a sm

Mar 10, 2022
Comments
  • Spaces between words

    Spaces between words

    After conversion spaces between words are lost.

    Example: <p><strong>How</strong> <em>are</em> you?</p> Expected output: "How are you?"

    Is converted to: <p><strong>How</strong><em>are</em>you?</p> Actual output: "Howareyou?"

    bug 
    opened by emecs 4
  • Adjusted string trim to preserve spaces

    Adjusted string trim to preserve spaces

    • Removed String.trim() from textContent handling
    • Added more specific cleanup for linebreaks, and double spaces
    • Individual spaces between words, regardless of elements, are now preserved
    opened by jahilldev 0
Releases(1.3.2)
Owner
James Hill
Technical Lead @groupon 💚. Performance advocate ⏱️. Generally pleasant fellow.
James Hill
A lightweight (~2kB) library to create range sliders that can capture a value or a range of values with one or two drag handles

range-slider-input A lightweight (~2kB) library to create range sliders that can capture a value or a range of values with one or two drag handles. Ex

Utkarsh Verma 42 Dec 24, 2022
Lightweight vanilla js modal component (just 2kb) , pure javascript Modal

Lightweight vanilla js modal component (just 2kb) pure javascript Modal , This is just 2kb Lightweight vanilla js modal component with zero dependenci

Salah Eddine Lalami 12 Dec 12, 2022
Avoid CORS issues by using API Routes from Next.js

CORS Demo Avoid CORS issues by using API Routes from Next.js. Get Started Clone the repo git clone [email protected]:gregrickaby/cors-demo.git CD into co

Greg Rickaby 2 Sep 30, 2022
Completely free TS/JS one-file source code snippets with tests, which can be copied to avoid extra dependencies (contributions welcome).

TinySource Completely free TS/JS one-file source code snippets with tests, which can be copied to avoid extra dependencies (contributions welcome). Sn

null 81 Jan 3, 2023
Avoid setting up a project from scratch. Start using VRTTV 🎉

VRTTV Boilerplate Avoid setting up a project from scratch. Start using VRTTV ?? View Demo · Report Bug · Request Feature ?? What’s this? Are you tired

Diego Do Santos 32 Nov 24, 2022
Dank Memer (Selfbot) Farm with slash commands support and random delays and breaks to avoid any suspicion

Slashy Slashy is a Dank Memer (Selfbot) Farm with slash commands support and random delays and breaks to avoid any suspicion. This is completely undet

Taha Gorme 16 Dec 30, 2022
A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM deffiniation and appropriate file structure.

Welcome to function-stencil ?? A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM

Ben Smith 21 Jun 20, 2022
Tries to execute sync/async function, returns a specified default value if the function throws

good-try Tries to execute sync/async function, returns a specified default value if the function throws. Why Why not nice-try with it's 70+ million do

Antonio Stoilkov 14 Dec 8, 2022
Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called

bun-livereload Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called. import liveRelo

Jarred Sumner 19 Dec 19, 2022
The 2Kb smallest Chat component.

tidi Meet tidi, the 2kb bubble chat component for any website... made using preact, running with a 4MB compiled backend service. FrontEnd Backend Disc

darker 72 Dec 11, 2022