Open textreme opened 11 months ago
extract your katex statement in md/mdx file and import it in code file (js/ts)
@B2o5T Thanks for your reply. Could you provide an example? Would this solution be appropriate in a case where there would be many katex statements in the component showing up in multiple places in the mdx file?
please provide your raw mdx file
Please share code of your components, so I could reproduce it
Please attach here your content on share a link to repo, I don’t want to download untrusted zip file
sorry - it was on private - should work now.
I needed some dynamically-rendered math in my components. I wrote a small wrapper function that calls KaTeX at run time:
import React from "react";
import autoRender from "katex/contrib/auto-render";
/**
* Render content that may have inline math in it. Rendering is done via KaTeX.
*/
export function MathRender({ content }: { content: string }) {
const ref = React.useRef<HTMLDivElement>(null);
React.useLayoutEffect(() => {
if (ref.current && content.includes("$")) {
autoRender(ref.current, {
delimiters: [{ left: "$", right: "$", display: false }],
});
}
}, [ref.current, content]);
return <span ref={ref}>{content}</span>;
}
Then you can use <MathRender content="\\frac{2}{3}" />
in your source.
@siefkenj cool and thanks - is this your solution to get Katex to run within a component on a page in Nextra?
@siefkenj cool and thanks - is this your solution to get Katex to run within a component on a page in Nextra?
Yes
@B2o5T curious if there are other ways (than siefkenj's wrapper function) to get Katex to work inside a component in a .mdx file
// my-page.mdx
<MyComponent>
```math
\\frac{2}{3}
And you should receive rendered latex as `children` prop in your `MyComponent` component
@siefkenj thanks for your snippet. i tried putting your snippet into components and then using <MathRender content="\\frac{2}{3}" />
on a page, but it didn't render came out as '\frac{2}{3}'. could you share screenshots of your file tree/example of it working for you?
`import React from "react"; import autoRender from "katex/contrib/auto-render";
/**
@B2o5T @siefkenj would your solutions work in JSON files? Basically, I'm trying to avoid storing JSX in JSON/.tsx files because a) I will be using a LOT of Katex/Latex and b) bc of the enormous workaround, one of the reasons I chose Nextra was bc of out-of-the-box Katex.
I took both of your leads and created a component: `// components/KaTeXRender.js import { InlineMath, BlockMath } from 'react-katex';
export default function Katex({ latex, block = false }) {
return block ?
@textreme You can see my project and the usage of MathRender
here: https://github.com/siefkenj/alfonso-calculus-materials/blob/f72bc8be6dde0aadbf9330d3075ca66a7272bf7e/website/components/question-preview.tsx#L53
Katex works when $...$ is input directly in the .mdx file; however, it does not render $...$ in a component in the .mdx file. Does anyone know how to get Katex to work in components in nextra?