Skip to content

Instantly share code, notes, and snippets.

@hisui
Created July 1, 2022 07:52
Show Gist options
  • Save hisui/255518e2fe3ffdbe1e5a4aa07436f153 to your computer and use it in GitHub Desktop.
Save hisui/255518e2fe3ffdbe1e5a4aa07436f153 to your computer and use it in GitHub Desktop.
highlight.js + React
import React, { ReactElement, useMemo } from "react"
import hljs from "highlight.js"
import 'highlight.js/styles/dark.css'
export function Code(props: { lang: string, text: string }): ReactElement {
const { value } = useMemo(() =>
hljs.highlight(props.lang, trimMargin(props.text)),
[props.lang, props.text]
)
return <pre className="hljs"><code dangerouslySetInnerHTML={{ __html: value }} /></pre>
}
function trimMargin(src: string): string {
const rows = src.trimEnd().split("\n")
for (let i = 0; i < rows.length; ++i) {
const rem = rows[i].trimStart().length
if (rem > 0) {
const margin = rows[i].length - rem
return rows.slice(i).map(e => e.slice(margin)).join("\n")
}
}
return src
}
import React from "react"
import { Code } from "./highlight"
function Index() {
return <div className="container-fluid">
<Code lang="javascript" text={`
for (;;) {
window.alert("Hello, World!")
}
`} />
</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment