|
| 1 | +/* |
| 2 | +Copyright 2017 Michael Telatynski <7t3chguy@gmail.com> |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import React from 'react'; |
| 18 | +import PropTypes from 'prop-types'; |
| 19 | +import {highlightBlock} from 'highlight.js'; |
| 20 | + |
| 21 | +export default class SyntaxHighlight extends React.Component { |
| 22 | + static propTypes = { |
| 23 | + className: PropTypes.string, |
| 24 | + children: PropTypes.node, |
| 25 | + }; |
| 26 | + |
| 27 | + constructor(props, context) { |
| 28 | + super(props, context); |
| 29 | + |
| 30 | + this._ref = this._ref.bind(this); |
| 31 | + } |
| 32 | + |
| 33 | + // componentDidUpdate used here for reusability |
| 34 | + // componentWillReceiveProps fires too early to call highlightBlock on. |
| 35 | + componentDidUpdate() { |
| 36 | + if (this._el) highlightBlock(this._el); |
| 37 | + } |
| 38 | + |
| 39 | + // call componentDidUpdate because _ref is fired on initial render |
| 40 | + // which does not fire componentDidUpdate |
| 41 | + _ref(el) { |
| 42 | + this._el = el; |
| 43 | + this.componentDidUpdate(); |
| 44 | + } |
| 45 | + |
| 46 | + render() { |
| 47 | + const { className, children } = this.props; |
| 48 | + |
| 49 | + return <pre className={`${className} mx_SyntaxHighlight`} ref={this._ref}> |
| 50 | + <code>{ children }</code> |
| 51 | + </pre>; |
| 52 | + } |
| 53 | +} |
0 commit comments