javascript - 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 console
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:
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:
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:
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
解决方案
推荐阅读
- opencv - 如何检测大小可能不同的部分矩形
- c# - ASP.NET Core 自定义验证创建模型的新实例
- android - React-native - 应用程序在模拟器上运行但不在真实设备中
- eclipse - 如何使用 Eclipse EMF 从方法中返回类型列表?
- python - How can I save it so the e-mail script can read/send it?
- data-structures - 来自未排序数组的二叉树
- xml - 带有adobe pdfmark的文本不可见,为什么?
- android - android : How to filter items in firebase by referring another database reference property
- javascript - 在 Promise.all() 中处理来自每个承诺的响应对象
- python - Python package: Can I look for config/yml file from project directory which called it?