Skip to main content
Version: App Router (1.5+)

Escaping & Sanitization

As you're probably aware, React won't render raw HTML by default. If you want to do so you must use dangerouslySetInnerHTML.

This page describes some of the utility functions and components provided by the framework to help with escaping & sanitization when rendering raw markup.

The SafeHtml component is the recommended way to render HTML content safely. It automatically sanitizes HTML content using wpKsesPost and provides a clean API:

import { SafeHtml } from '@headstartwp/core/react';

<SafeHtml html="<p>some raw html</p>" />

wpKsesPost

This function sanitizes HTML content with requirements similar to wp_kses_post. If you are rendering arbitrary HTML markup you should probably run the markup through this function first.

import { wpKsesPost } from '@headstartwp/core';

const markup = { __html: wpKsesPost('<p>some raw html</p>') };
return <div dangerouslySetInnerHTML={markup} />;

Note: It's recommended to use the SafeHtml component instead of manually using wpKsesPost with dangerouslySetInnerHTML.

stripTags

This function simply strips any html tags from a string. This can be useful in contexts where you don't want any HTML to be rendered.

import { stripTags } from '@headstartwp/core';

return <h1>{stripTags('this is a title <span>without a span</span>')}</h1>;

BlocksRenderer

When using BlocksRenderer your markup already goes through wpKsesPost so there's nothing else you need to worry about.

HtmlDecoder

Sometimes you might just want to decode some HTML entities without actually rendering any HTML tags. For this purpose you can use the HtmlDecoder component.

import { HtmlDecoder } from '@headstartwp/core/react';

<h1>
<HtmlDecoder html="Hello world! &#8211; foo bar &#8211;"/>
</h1>

decodeHtmlSpeciaChars

This function will decode a pre-defined set of html special chars.

import { decodeHtmlSpeciaChars } from '@headstartwp/core';

decodeHtmlSpeciaChars('Hello world! &#8211; foo bar &#8211');