Search code examples
javascriptreactjsnpmkatex

How can I use KaTeX in React project?


How can KaTex be used in a React project? I read through documentation on NPM and still don't get it.

I don't quite see how katex.render and katex.renderToString can be applied to React.


Solution

  • katex.render needs a DOM element to render in, you can get one with a useRef hook.

    const KaTeXComponent = ({texExpression}) => {
        const containerRef = useRef();
    
        useEffect(() => {
            katex.render(texExpression, containerRef.current);
        }, [texExpression]);
    
        return <div ref={containerRef} />
    }