I use react-markdown
library and prismjs
for highlighting code in my project. But the highlighting doesn't working always after I change route.
For example,
- I have markdown code in
TestPage
, and the url path in browser islocalhost:3000/test
.
const markdown = `## How about some code?
\`\`\`js
var React = require('react');
var Markdown = require('react-markdown');
React.render(
<Markdown source="# Your markdown here" />,
document.getElementById('content')
);
\`\`\``;
- If I start the project, the default rendering page is
localhost:3000
, when I jump to the routelocalhost:3000/test
, the markdown syntax works, but the code highlighting doesn't work. The rendered html code shows as below:
<h2>How about some code?</h2>
<pre>
<code class="language-js">
var React = require('react');
var Markdown = require('react-markdown');
React.render(
<Markdown source="# Your markdown here" />,
document.getElementById('content')
);
</code>
</pre>
- If I refresh the page with url
localhost:3000/test
, then the highlighting works. The rendered html code shows as below:
<pre class=" language-js">
<code class=" language-js">
<span class="token keyword">var</span> React
<span class="token operator">=</span>
<span class="token function">require</span>
<!-- For simplify, I omit the left code -->
</code>
</pre>
- But if I routes to other page and back to
testpage
, the code highlighting doesn't work again.
Why does that happen? I want to know what's problem of my code logic.
The code below is how i use react-markdown
:
<ReactMarkdown source={markdown} renderers={{ CodeBlock }} />
CodeBlock:
export default function CodeBlock({ language, value }) {
const codeEle = useRef(null);
useEffect(() => {
console.log('CodeBlock: useEffect');
Prism.highlightElement(codeEle, false);
}, [codeEle]);
return (
<pre>
<code ref={codeEle} className={`language-${language}`}>
{value}
</code>
</pre>
);
}
P.S.
- I use
react-router-dom
, have aSwitch
in App/index.js
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/test" component={TestPage} />
</Switch>