Skip to content

Instantly share code, notes, and snippets.

@Digital39999
Created June 26, 2024 08:58
Show Gist options
  • Save Digital39999/204c3402f7c69f2cc7e975107f12c2c6 to your computer and use it in GitHub Desktop.
Save Digital39999/204c3402f7c69f2cc7e975107f12c2c6 to your computer and use it in GitHub Desktop.
import { isValidElement, Children } from 'react';
import pkg from 'katex';
export function Math({ expression }: { expression: string }) {
const equation = pkg.renderToString(expression, { throwOnError: false });
return <span dangerouslySetInnerHTML={{ __html: equation }} />;
}
export function MathText({ children }: { children: React.ReactNode; }) {
const parseMathExpressions = (text: string) => {
const parts = [];
let lastIndex = 0;
const regex = /\$(.+?)\$/g;
let match;
while ((match = regex.exec(text)) !== null) {
const mathExpression = match[1];
if (match.index > lastIndex) parts.push(text.slice(lastIndex, match.index));
parts.push(<Math key={match.index} expression={mathExpression} />);
lastIndex = regex.lastIndex;
}
if (lastIndex < text.length) parts.push(text.slice(lastIndex));
return parts;
};
const renderChildren = (children: React.ReactNode) => {
return Children.map(children, (child) => {
if (typeof child === 'string') return parseMathExpressions(child);
else if (isValidElement(child)) return child;
else return <></>;
});
};
return <>{renderChildren(children)}</>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment