highlightjs / highlight.js

JavaScript syntax highlighter with language auto-detection and zero dependencies.
https://highlightjs.org/
BSD 3-Clause "New" or "Revised" License
23.59k stars 3.58k forks source link

highlight.js , ckededitor5 , next.js Element previously highlighted. To highlight again, first unset `dataset.highlighted`. #4122

Open uchar opened 3 hours ago

uchar commented 3 hours ago

I'm using Next.js and ckeditor for generating content . code is :

'use client'
import React, { useEffect, useRef } from 'react'
import Box from '@mui/material/Box'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'
import '@/common/components/Editor/Content.css'
import 'highlight.js/styles/ascetic.css'

interface ParseContentProps {
  content: string
}

export const ParseContent = ({ content }: ParseContentProps) => {
  const contentRef = useRef<HTMLDivElement>(null)

  const sanitizedContent = DOMPurify.sanitize(content)

  useEffect(() => {
    const codeBlocks = contentRef.current?.querySelectorAll('pre code')
    codeBlocks?.forEach((block) => {
      hljs.highlightElement(block as HTMLElement)
    })
  }, [sanitizedContent])

  return (
    <div className="ck-content">
      <Box
        ref={contentRef}
        dangerouslySetInnerHTML={{
          __html: sanitizedContent,
        }}
      />
    </div>
  )
}

But it doesn't highlight anything and keep giving error :

Element previously highlighted. To highlight again, first unset `dataset.highlighted`. <code class=​"language-javascript hljs" data-highlighted=​"yes">​…​</code>​

if I use

'use client'
import React, { useEffect, useRef } from 'react'
import Box from '@mui/material/Box'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'
import '@/common/components/Editor/Content.css'
import 'highlight.js/styles/ascetic.css'

interface ParseContentProps {
  content: string
}

export const ParseContent = ({ content }: ParseContentProps) => {
  useEffect(() => {
    hljs.highlightAll()
  }, []) // Dependency on sanitizedContent to re-run on change

  return (
    <div className="ck-content">
      <pre>
        <code className="language-javascript">{'let a=5;'}</code>
      </pre>
    </div>
  )
}

It starts working , not sure what is causing the first example not working does it have something to do with SSR ? not sure what I need to change , first one seems fine to me , Is this a highligh.js bug ?

joshgoebel commented 2 hours ago

Element previously highlighted.

There is no reason to highlight an element twice.

does it have something to do with SSR

That would make sense, if it was highlighted server-side it does not need to be re-highlighted on the client - it's already highlighted.