Skip to content

Instantly share code, notes, and snippets.

@theodorosploumis
Forked from natterstefan/HTMLToReact.tsx
Created May 12, 2022 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theodorosploumis/a61efb56b530427620e53002efababe1 to your computer and use it in GitHub Desktop.
Save theodorosploumis/a61efb56b530427620e53002efababe1 to your computer and use it in GitHub Desktop.
html-react-parser | TypeScript solution

html-react-parser | TypeScript Error - instanceof Element always return false with Next.js

visitors

This is the related issue and the solution that is by the time you read this probably merged already.

/**
* Works in Next.js 10.x
*/
import React from 'react'
import parse, {
domToReact,
attributesToProps,
Element,
HTMLReactParserOptions,
} from 'html-react-parser'
/**
* I got some TS issues, that's why I came up with `typedDomNode`.
*
* Related issues:
* @see https://github.com/remarkablemark/html-react-parser/issues/221#issuecomment-771600574
*/
const options: HTMLReactParserOptions = {
replace: domNode => {
const typedDomNode = domNode as Element
if (typedDomNode.attribs && typedDomNode.name === 'a') {
return (
<a
{...attributesToProps(typedDomNode.attribs)}
className="underline text-primary-500"
target="_blank"
>
{typedDomNode.children && domToReact(typedDomNode.children, options)}
</a>
)
}
return false
},
}
export const HTMLToReact = ({ html }: { html: string }) => {
return <>{parse(html, options)}</>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment