0

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 is localhost: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 route localhost: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(
      &lt;Markdown source="# Your markdown here" /&gt;,
      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 a Switch in App/index.js
<Switch>
  <Route exact path="/" component={HomePage} />
  <Route path="/test" component={TestPage} />
</Switch>
Gasin
  • 51
  • 2
  • 7

1 Answers1

3

I had the same problem as you. And I found it's about the timing of loading to the highlight.js. I used the code below to solve this problem.

useEffect(()=>{
    hljs.initHighlighting.called = false;
    hljs.initHighlighting();
},[]);

You may also need to include highligh.js and the style from highlight.js.

import hljs from 'highlight.js'
import "highlight.js/styles/github.css";

I'm not sure if this is the correct way to solve the problem. It seems a little redundant because you need to add this snippet of code to every page which you want to render the markdown. But it works. I hope this will help you out.