forked from tangly1024/NotionNext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKatexReact.js
53 lines (47 loc) · 1.13 KB
/
KatexReact.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import KaTeX from 'katex'
import React from 'react'
const TeX = ({
children,
math,
block,
errorColor,
renderError,
settings,
as: asComponent,
...props
}) => {
const Component = asComponent || (block ? 'div' : 'span')
const content = (children ?? math)
const [state, setState] = React.useState({ innerHtml: '' })
React.useEffect(() => {
try {
const innerHtml = KaTeX.renderToString(content, {
displayMode: true,
errorColor,
throwOnError: !!renderError,
...settings
})
setState({ innerHtml })
} catch (error) {
if (error instanceof KaTeX.ParseError || error instanceof TypeError) {
if (renderError) {
setState({ errorElement: renderError(error) })
} else {
setState({ innerHtml: error.message })
}
} else {
throw error
}
}
}, [block, content, errorColor, renderError, settings])
if ('errorElement' in state) {
return state.errorElement
}
return (
<Component
{...props}
dangerouslySetInnerHTML={{ __html: state.innerHtml }}
/>
)
}
export default React.memo(TeX)