Skip to content

Instantly share code, notes, and snippets.

@natterstefan
Last active April 8, 2024 13:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save natterstefan/3bc712eca6ff88781d687b7240a78cc1 to your computer and use it in GitHub Desktop.
Save natterstefan/3bc712eca6ff88781d687b7240a78cc1 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)}</>
}
@adam-tan
Copy link

thank you very good !!!

@natterstefan
Copy link
Author

Your welcome @adam-tan!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment