#Need help with a type assertion when using html-react-parser

6 messages · Page 1 of 1 (latest)

next locust
#

I have some HTML content that is being returned from a CMS that I wish to display in a NextJS V13 app. I am using the html-react-parser package rather than dangerouslySetHtml to parse the HTML content as I also wish to replace embedded <video> tags with a custom <VideoPlayer> React component

My code looks like this:

"use client"

import parse, { DOMNode, Element, HTMLReactParserOptions } from "html-react-parser"
import { sanitize } from "isomorphic-dompurify"
import VideoPlayer from "@/components/video-player"

export default function ArticleContent({ content }: { content: string }) {
  const parserOptions: HTMLReactParserOptions = {
    replace: (domNode: DOMNode) => {
      // Replace embedded <video> tags with our custom VideoPlayer component
      if (domNode instanceof Element && domNode.name === "video") {
        // TODO: Figure out correct type assertions so typesript doesn't complain
        // @ts-ignore
        const src = domNode.children[0].next.attribs.src
        return <VideoPlayer src={src} />
      }
    },
  }

  return (
    <div className="prose-img:rounded-2xl prose-img:shadow-xl prose-img:shadow-slate-900 dark:prose-img:shadow-gray-500">
      {parse(sanitize(content), parserOptions)}
    </div>
  )
}

Typescirpt is telling me:

Property 'attribs' does not exist on type 'ChildNode'.
  Property 'attribs' does not exist on type 'Comment'.ts(2339)
⚠ Error (TS2339)

... and "src" is typed as "any".

I've tried several different type assertions to try and get Typescript not to complain, but so far nothing seems to work. Can anyone point me in the right direction to figuring out how to type the domNode path so that TS will stop complaining about the assignment?

daring axle
#

@next locust the code you provided is incorrect
there is an if statement inside of that parserOptions variable declaration
looks like you tried to remove some code to provide a minimal example, but forgot to fix a few things

#

also, it's missing the most important parts: the domNode variable

#

what type is it? where is it coming from? how are you calling the sanitize and parser lib?

#

it's the core part of the problem, yet you removed all of that

next locust
#

@daring axle You're right...I did try to provide a minimal example and accidentally removed a line (there are other DOM elements I'm replacing that are working fine, so I removed that code). I've updated the original post with the correct replacement object that the parser is expecting. This code works, notwithstanding TS complaining about that src assignment. The domNode variable is passed into the replacement function by html-react-parser that is passed on to the parse function.