javascript - How can I use KaTeX in React project? - Stack Overflow

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

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.

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.

Share Improve this question edited Feb 23, 2022 at 9:24 mkrieger1 23.6k7 gold badges64 silver badges82 bronze badges asked Feb 22, 2022 at 20:00 zmkmzmkm 1472 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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} />
}

This is a modified version of @Quentin code for React with TypeScript:

import katex from "katex";
import { useEffect, useRef } from "react";
import "katex/dist/katex.min.css";

function KaTeX({ texExpression, className }: { texExpression: string, className: string }) {
  const containerRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    katex.render(texExpression, containerRef.current as HTMLInputElement);
  }, [texExpression]);

  return <div ref={containerRef} className={className} />;
}

export default KaTeX;

And this is what you need for installation npm i katex @types/katex.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745332525a4622947.html

相关推荐

  • javascript - How can I use KaTeX in React project? - Stack Overflow

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

    6小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信