Reputation: 501
I fetch code snippets from the server to display.
If I want to display the code, I attach the node to DOM. If there is no code to display, I remove the node from DOM.
I'm using highlight.js to highlight the code.
To highlight:
<script>hljs.initHighlightingOnLoad();</script>
But the problem is, it only highlights the code on load as the method name indicates.
So, I need to check and highlight the code.
I guess refreshing the page after every request is not a solution.
I've tried this SO answer:
hljs.initHighlighting.called = false;
hljs.initHighlighting();
But I don't see any highlighting.
How can I highlight the code dynamically whenever I want in ReactJS?
Upvotes: 0
Views: 1768
Reputation: 2523
To dynamically highlight certain nodes(which your code must be between <code><pre></pre></code>
) in your DOM:
hljs.highlightBlock(document.getElementById("codeblock"));
Where, codeblock
is the id of your node. For example, <code id=""codeblock><pre></pre></code>
.
What we do here is, we are using hljs
method to highlight only particular element/node in your DOM.
And you are adding and removing elements from your DOM. So, you need to check if any new element that you are intended to highlight is added or not. And call the above function to highlight the code.
To check for mutations in your DOM, you can use MutationObserver to a listen to the changes and call the above function to highlight the code.
Note: Don't use setTimeout()
to poll for changes! It effects performance of the website.
If you find MutationObserver difficult to implement, you can use this awesome library arrive.
Either download .min.js
and include it in your browser or Install the npm package of arrive
:
$ npm install -S arrive
If you are using through npm, import it in your code like require("arrive");
Write a callback function for arrive
:
highlight(){
if(document.getElementById("codeblock") != null){
hljs.highlightBlock(document.getElementById("codeblock"));
}
}
To register arrive
: Call this in your constructor()
document.arrive("#codeblock", () => this.highlight());
It should do the work.
Upvotes: 1