Skip to content

Instantly share code, notes, and snippets.

@filipesmedeiros
Created December 23, 2022 01:23
Show Gist options
  • Save filipesmedeiros/c10b3065e20c4d61ba746ab78c6a7a9e to your computer and use it in GitHub Desktop.
Save filipesmedeiros/c10b3065e20c4d61ba746ab78c6a7a9e to your computer and use it in GitHub Desktop.
react-katex for React Server Component
import katex, { type KatexOptions, ParseError } from 'katex'
import { type ComponentProps, type ReactElement } from 'react'
export type Props<T extends keyof JSX.IntrinsicElements = 'div'> =
ComponentProps<T> &
Partial<{
as: T
block: boolean
errorColor: string
renderError: (error: ParseError | TypeError) => ReactElement
settings: KatexOptions
}> & {
math: string
}
export default async function TeX({
children,
math,
block,
errorColor,
renderError,
settings,
as: asComponent,
...props
}: Props) {
// @ts-expect-error CSS not JS
await import('katex/dist/katex.min.css')
const Component = asComponent || (block ? 'div' : 'span')
const content = (children ?? math) as string
let innerHtml: string
try {
innerHtml = katex.renderToString(content, {
displayMode: !!block,
errorColor,
throwOnError: !!renderError,
...settings,
})
} catch (error) {
if (error instanceof ParseError || error instanceof TypeError) {
if (renderError) {
return renderError(error)
} else {
innerHtml = error.message
}
} else {
throw error
}
}
return (
<Component {...props} dangerouslySetInnerHTML={{ __html: innerHtml }} />
)
}
@filipesmedeiros
Copy link
Author

This is heavily inspired by @MatejBransky 's react-katex

@alfonsusac
Copy link

alfonsusac commented Aug 10, 2023

How do I react to a gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment