Created
April 12, 2017 10:26
-
-
Save jamesknelson/b6cb32764ca4e769b38d708df987f049 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { PureComponent, PropTypes } from "react" | |
import Prism from 'prismjs' | |
const codeBlockAliases = { | |
'js': 'jsx', | |
'html': 'markup', | |
'mdx': 'markdown', | |
'md': 'markdown', | |
} | |
function highlight(str, lang) { | |
if (!lang) { | |
return str | |
} else { | |
lang = codeBlockAliases[lang] || lang | |
require(`prismjs/components/prism-${lang}.js`) | |
if (Prism.languages[lang]) { | |
return Prism.highlight(str, Prism.languages[lang]) | |
} else { | |
return str | |
} | |
} | |
} | |
export default class HighlightedCodeBlock extends PureComponent { | |
static propTypes = { | |
className: PropTypes.string, | |
style: PropTypes.object, | |
language: PropTypes.string, | |
source: PropTypes.string, | |
} | |
render() { | |
const language = this.props.language | |
const className = this.props.className + ' language-'+(language === 'mdx' ? 'markdown' : language) | |
const source = this.props.source.replace(/^\n|\n$/g, '') | |
const highlighted = highlight(source, language) | |
return ( | |
<pre className={className} style={this.props.style}> | |
<code dangerouslySetInnerHTML={{ __html: highlighted }} /> | |
</pre> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment