Created
December 23, 2022 01:23
-
-
Save filipesmedeiros/c10b3065e20c4d61ba746ab78c6a7a9e to your computer and use it in GitHub Desktop.
react-katex for React Server Component
This file contains 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 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 }} /> | |
) | |
} |
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
This is heavily inspired by @MatejBransky 's
react-katex