-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathHighlight.js
More file actions
73 lines (58 loc) · 1.53 KB
/
Highlight.js
File metadata and controls
73 lines (58 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import React, { Component } from "react";
import PropTypes from "prop-types";
import hljs from "highlight.js";
import "highlight.js/styles/monokai-sublime.css";
const registeredLanguages = {};
class Highlight extends Component {
constructor(props) {
super(props);
this.state = { loaded: false };
this.codeNode = React.createRef();
}
componentDidMount() {
const { language } = this.props;
if (language && !registeredLanguages[language]) {
try {
const newLanguage = require(`highlight.js/lib/languages/${language}`);
hljs.registerLanguage(language, newLanguage);
registeredLanguages[language] = true;
this.setState({ loaded: true }, this.highlight);
} catch (e) {
console.error(e);
throw Error(`Cannot register the language ${language}`);
}
} else {
this.setState({ loaded: true });
}
}
componentDidUpdate() {
this.highlight();
}
highlight = () => {
this.codeNode &&
this.codeNode.current &&
hljs.highlightBlock(this.codeNode.current);
};
render() {
const { language, children } = this.props;
const { loaded } = this.state;
if (!loaded) {
return null;
}
return (
<pre className="rounded">
<code ref={this.codeNode} className={language}>
{children}
</code>
</pre>
);
}
}
Highlight.propTypes = {
children: PropTypes.node.isRequired,
language: PropTypes.string,
};
Highlight.defaultProps = {
language: "json",
};
export default Highlight;