首页 > 解决方案 > Prism.js not working properly in some cases React

问题描述

I have a react & typescript application. It's a blog post and I'm fetching markdown from an API. I'm parsing it using showdown.

The problem is that the syntax highlighting is not working on the fetched code but some of my own code is working fine:

export default function BlogDetail() {

    const mdContainerRef = useRef<null | HTMLDivElement>(null);

    useEffect(() => {
        (async () => {
            if (mdContainerRef.current) {
                const parser = new Converter();
                const html = parser.makeHtml(data.body_markdown);

                Prism.highlightAll();

                mdContainerRef.current.innerHTML = html
                    .replaceAll('<h3', '<h3 class="text-4xl mt-7 mb-2"')
                    .replaceAll('<h5', '<h5 class="text-xl mt-5"');
                // .replaceAll(
                //  '<pre><code class="js language-js"',
                //  '<pre class="javascript language-javascript"><code class="javascript language-javascript"'
                // ).replaceAll('<pre><code class="css language-css"', '<pre class="css // language-css"><code class="css language-css"');
            }

            setArticle(data);
        })();
    }, [slug, mdContainerRef]);

    return (
            <pre>
                <code className='language-javascript'>
                    {`onSubmit(e) {
                        e.preventDefault();
                        const job = {
                            title: 'Developer',
                            company: 'Facebook' 
                        };
                    }`}
                </code>
            </pre>

            <div ref={mdContainerRef}></div>
    );
}

The pre & code elements which I'm rendering have perfect syntax highlighting(I've imported prism.css too). However, the fetched markup is not showing any signs of syntax highlighting. Here's a pic of the elements in the consoleenter image description here

As you can see, there is some formatting, for example, the font is changed and so is the color of the text.

Now, here's a pic of some css code:

enter image description here

As you can see, both of them don't have syntax highlighting. However, let me draw your attention to the the pre and code elements:

enter image description here

Ignore the indentation, but the highlighting seems to be working fine.

If you have noticed, there's some commented code above. When I uncomment that, it looks like this:

enter image description here

The background has changed but there's still no syntax highlighting.

Any help is appreciated! Thanks in advance!

PS: I'm open to use other highlighting options, please provide a demo/sample code or give a link to the docs

标签: javascriptreactjsprismjs

解决方案


推荐阅读