Giter Club home page Giter Club logo

react-katex's Introduction

react-katex


Display math expressions with KaTeX and React.

Examples

(based on the https://github.com/talyssonoc/react-katex)
(the readme and the demo are "forked" from https://github.com/talyssonoc/react-katex)


Comparison with react-katex: talyssonoc/react-katex#49.

npm type definitions

Installation

  $ npm install katex @matejmazur/react-katex
  # or
  $ yarn add katex @matejmazur/react-katex

Usage

import 'katex/dist/katex.min.css';
import TeX from '@matejmazur/react-katex';

Inline math

Display math in the middle of the text.

ReactDOM.render(
  <TeX math="\int_0^\infty x^2 dx" />,
  document.getElementById('math')
);

// or

ReactDOM.render(
  <TeX>\int_0^\infty x^2 dx</TeX>,
  document.getElementById('math')
);

It will be rendered like this:

Inline math

Block math

Display math in a separated block, with larger font and symbols.

ReactDOM.render(
  <TeX math="\int_0^\infty x^2 dx" block />,
  document.getElementById('math')
);

// or

ReactDOM.render(
  <TeX block>\int_0^\infty x^2 dx</TeX>,
  document.getElementById('math')
);

It will be rendered like this:

Block math

Note:
Don't forget to import KaTeX CSS file.

import 'katex/dist/katex.min.css';

Error handling

Default error message

By default the error rendering is handled by KaTeX. You can optionally pass errorColor (defaults to #cc0000) as a prop:

ReactDOM.render(
  <TeX math={'\\int_0^\\infty x^2 dx \\inta'} errorColor={'#cc0000'} />,
  document.getElementById('math')
);

This will be rendered like so:

KaTeX error

Custom error message

It's possible to handle parse errors using the prop renderError. This prop must be a function that receives the error object and returns what should be rendered when parsing fails:

ReactDOM.render(
  <TeX
    math="\\int_{"
    renderError={(error) => {
      return <b>Fail: {error.name}</b>;
    }}
  />,
  document.getElementById('math')
);

// The code above will render '<b>Fail: ParseError</b>' because it's the value returned from `renderError`.

This will render <b>Fail: ParseError</b>:

renderError

Custom wrapper component

You can change the wrapper component (block math uses div and inline uses span) by whatever you want via props.as attribute.

ReactDOM.render(
  <TeX
    math="y = x^2"
    as="figcaption"
  />,
  document.getElementById('math')
);

Escaping expressions

In addition to using the math property, you can also quote as a child allowing the use of { } in your expression.

ReactDOM.render(
  <TeX>{'\\frac{\\text{m}}{\\text{s}^2}'}</TeX>,
  document.getElementById('math')
);

Or Multiline

ReactDOM.render(
  <TeX>{`\\frac{\\text{m}}
{\\text{s}^2}`}</TeX>,
  document.getElementById('math')
);

However, it can be annoying to escape backslashes. This can be circumvented with the String.raw tag on a template literal when using ES6.

ReactDOM.render(
  <TeX>{String.raw`\frac{\text{m}}{\text{s}^2}`}</TeX>,
  document.getElementById('math')
);

Backticks must be escaped with a backslash but would be passed to KaTeX as \`. A tag can be created to replace \` with `

const latex = (...a) => String.raw(...a).replace('\\`', '`');
ReactDOM.render(<TeX>{latex`\``}</TeX>, document.getElementById('math'));

You can even do variable substitution

const top = 'm';
const bottom = 's';
ReactDOM.render(
  <TeX>{String.raw`\frac{\text{${top}}}{\text{${bottom}}^2}`}</TeX>,
  document.getElementById('math')
);

Configuring KaTeX

You can change directly all KaTeX options via props.settings:

Example of adding a custom macro:

ReactDOM.render(
  <TeX settings={{ macros: { '*': '\\cdot' } }}>y = k * x + c</TeX>
);

Result:

macros

react-katex's People

Contributors

dependabot[bot] avatar izhaki avatar matejbransky avatar renovate-bot avatar shilangyu avatar tymick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-katex's Issues

Rendering to string results in empty span

Describe the bug
When trying to user the renderToString function available in react-dom/server, the resulting HTML output does not contain the equation.

To Reproduce

import React from 'react';
import { renderToString } from 'react-dom/server';

import BlockMath from '@matejmazur/react-katex';

// KaTeX support
import 'katex/dist/katex.min.css'

function TeXter() {
  const tex = renderToString(<BlockMath math="f(x)=\lim_{x\to\infin}\int_a^b e^x" />);

  return (
    <div className="content" dangerouslySetInnerHTML={{__html: tex}}>

    </div>
  );
}
//...

Expected behavior
To return the complete HTML rendering of a given TeX equation.

Screenshots
This is the resulting HTML
immagine

  • OS: Windows 10 Pro, 1909
  • Browser: Firefox
  • Version: 85.0

Additional context
The react-katex package appears to be working just fine in this context

immagine

To get to this stage I just changed the import line to import {BlockMath} from 'react-katex';

Hi, it failed to display piecewise function

Describe the bug
When I use this lib to display piecewise function in "f(x) = \left{\begin{array}{ll}-x & \quad x \leq 0 \x & \quad x > 0\end{array}\right.",it alerted as "KaTeX parse error: Expected '}', got '&' at position 32: …n{array}{ll}-x &̲ quad x leq 0 x…"
. But this statement for PieceWise function works in https://katex.org/ wetsite.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency husky to v9
  • chore(deps): update dependency lint-staged to v15
  • chore(deps): update dependency parcel to v2
  • chore(deps): update dependency prettier to v3
  • chore(deps): update dependency react-error-boundary to v4
  • chore(deps): update dependency rimraf to v5
  • chore(deps): update dependency typescript to v5
  • chore(deps): update testing-library monorepo (major) (@testing-library/jest-dom, @testing-library/react)
  • 🔐 Create all rate-limited PRs at once 🔐

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
demo/package.json
  • katex 0.12.0
  • react 16.14.0
  • react-dom 16.14.0
  • @matejbransky/eslint-config 1.0.0-alpha.2
  • @matejbransky/prettier-config 1.0.0-alpha.2
  • @matejbransky/typescript-config 1.0.0-alpha.1
  • @types/katex 0.11.0
  • @types/react 16.14.5
  • @types/react-dom 16.9.11
  • eslint 6.8.0
  • parcel 1.12.4
  • prettier 2.2.1
  • rimraf 3.0.2
  • typescript 3.9.9
package.json
  • @matejbransky/eslint-config 1.0.0-alpha.2
  • @matejbransky/jest-preset 1.0.0-alpha.2
  • @matejbransky/prettier-config 1.0.0-alpha.2
  • @matejbransky/typescript-config 1.0.0-alpha.1
  • @testing-library/jest-dom 5.11.9
  • @testing-library/react 10.4.9
  • @types/katex 0.11.0
  • @types/react 16.14.5
  • @types/react-dom 16.9.11
  • eslint 6.8.0
  • husky 4.3.8
  • jest 26.6.3
  • katex 0.12.0
  • lint-staged 10.5.4
  • microbundle 0.12.4
  • prettier 2.2.1
  • react 16.14.0
  • react-dom 16.14.0
  • react-error-boundary 2.3.2
  • rimraf 3.0.2
  • snapshot-diff 0.8.1
  • typescript 3.9.9
  • katex >=0.9
  • react >=16
  • node >=12
  • yarn >=1.1

  • Check this box to trigger a request for Renovate to run again on this repository

React Server Component compatible version (with gist)

The gist

https://gist.github.com/filipesmedeiros/c10b3065e20c4d61ba746ab78c6a7a9e

Is your feature request related to a problem? Please describe.
The current version doesn't run on the server, although it needs no interactivity (in regular use cases). So a RSC seems logical.

Describe the solution you'd like
The one I provided (a RSC) or similar.

Describe alternatives you've considered
None necessary

Additional context
For use with frameworks like Next.js 13 on app dir

I just didn't know the best way to package this, and didn't have the dev env for your repo setup, so I though this would be an easier and more direct way to contribute. You can make all necessary adjustments :)

Some symbols create a new line in inline TeX

Describe the bug
When we write long strings with TeX that has block=false some symbols create a new line and I think that is not the expected result

To Reproduce
Steps to reproduce the behavior:

  • You can use any project that use react-katex (https://codesandbox.io/s/github/MatejMazur/react-katex/tree/master/demo)
  • Check that TeX is not using block prop
  • Write a long string and add some symbols near the end (for example) \cong or \cdot (this happens only with some symbols and not all the symbols)
  • Check the rendered TeX and see how it breaks after that symbols

Expected behavior
Should not create a new line if any symbols were added

Screenshots

Block prop false

Katex.-.Inline.mov

Block prop true

Katex.-.Block.mov

Desktop (please complete the following information):

  • OS: MacOS
  • Browser: Chrome
  • Version: 92.0.4515.159

Smartphone (please complete the following information):

N/A

No display mode & doesn’t work in Chrome?

Hello,

Thanks for making this package. I ran into a couple of issues when trying to render a simple formula:

<TeX
  block
  math={String.raw`F(x) = \int^a_b \frac{1}{3}x^3`}
  settings={{
    displayMode: true,
    output: 'mathml'
  }}
/>
  • This doesn’t render in display mode (I tried with and without block and settings.displayMode)
  • The default output is htmlAndMathml, just like KaTeX, but this does not correspond with the live examples (maybe because another version is used under the hood?)
  • The output doesn’t render in Chrome on macOS Catalina, but it does on Safari & Firefox

Any help would be greatly appreciated!

Module parse failed error when using NextJS

I'm trying to use katex and @matejmazur/react-katex with Next.js.

I'm getting this error: Failed to compile error:

./node_modules/@matejmazur/react-katex/src/index.tsx
Module parse failed: Unexpected token (11:9)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import KaTeX, { ParseError, KatexOptions } from 'katex';
| 
> const TeX: React.FC<TeXProps> = ({
|   children,
|   math,

I have this in my next.config.js file:

// next.config.js

const katex = require('katex')

module.exports = {
  future: {
    webpack5: true,
  },
  webpack: function (config, options) {
    config.experiments = {}
    return config
  },
  katex,
}

I think I'm missing something. Would anybody have any suggestions?

react-katex.modern.js fails to compile in Create React App

Describe the bug

After upgrading to @matejmazur/react-katex v3.1.2 in my Create React App project, the project now fails to compile, showing the following error message in the browser:

Failed to compile

./node_modules/@matejmazur/react-katex/dist/react-katex.modern.js 14:15
Module parse failed: Unexpected token (14:15)
File was processed with these loaders:
 * ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| }) => {
|   const E = c || (i ? "div" : "span"),
>         f = e ?? a,
|         [h, p] = n({
|     innerHtml: ""

This error occurred during the build time and cannot be dismissed.

This error also occurs with @matejmazur/react-katex v3.1.1, but my project does compile correctly with v3.1.0.

To Reproduce

If you don't mind cloning a branch of my project, that'll give you the most complete context for the error:

git clone --single-branch --branch react-katex-bug https://github.com/tywmick/rt-simulator.git
yarn
yarn start

Expected behavior

For my page to compile correctly like it did with v3.0.2.

Screenshots

"Failed to compile" error in Chrome

Desktop (please complete the following information):

  • OS: macOS 10.15.6 (19G73)
  • Browsers:
    • Chrome 84.0.4147.105 (Official Build) (64-bit)
    • Safari 13.1.2 (15609.3.5.1.3)
    • Firefox 79.0 (64-bit)

Additional context

I think I've figured out how to fix it, the issue being the new modern bundle being mapped to the "module" field in package.json. I'll write a PR with my fix next—I just felt like I should document the issue itself separately for some reason.

Automatic parsing of of text with latex delimiters

One missing feature that I'd love that is not built in into the original react-katex or katex itself is parsing text. This is normally achieved in katex by using the auto-render plugin. The structure I am thinking off is having a prop (e.g. parse) that you can pass to activate it, as well as some config to define which delimiters to use. There would be another file on the source folder (e.g. parse.ts) and it would be dynamically imported if the parse prop is true.

Inline Latex parsing

Is there any way to parse latex inside a text paragraph through component.

ex: "Solve this: $$c = 2\sqrt{3}$$"

I can do this through katex but don't find any way to achieve this using component, I don't know where and how many times Latex will be added in a paragraph so I'm wondering how to get this using component.

React 17 dependency

Can the dependencies be updated to work with React 17? I'm on react@"^17.0.1"

Currently, the dependency is react@"^15.32.2 || ^16.0.0" which would require installing with npm i react-katex --legacy-peer-deps

No TypeScript declaration file

Describe the bug
Since there are no types for this package, it doesn't work with TypeScript.

To Reproduce
Steps to reproduce the behavior:

  1. Import the package
  2. See that types are not installed
  3. Note that it won't compile with any .tsx file

Expected behavior
No compiler error, types exist and are accessible

Additional context
Add types to DefinitelyTyped for best results

TeX component crashing

Describe the bug
Currently the component completely crashes when Katex throws an exception, making the entire page go blank if that happens.

It is mentioned nowhere that you would need Error Boundaries. I would suggest either changing the documentation to add some form of error handling on the user-site, or handle the error in the component

To Reproduce
Katex crashes on the following input \begin{\pmatrix}. Render the Tex component with that input. It crashes.

Expected behavior
Either it not crashing, or mentioning in the documentation / usage that it can crash!

Replace microbundle with tsdx

Description

It seems that I need a lot of boilerplate around microbundle it doesn't contain settings for testing and TS. And it's frustrating that there are now a lot of warnings and errors when I install deps. Tsdx looks promising and it has support for testing right out of the box so I'll try to replace microbundle with tsdx.

Expected

Clean development environment.

Possible katex helper function

I am currently using the talyssonoc/react-katex and wanted to know if this library had helper functions such as

  • katex.__parse(value);
  • katex.renderToString(value, { displayMode: false, })

I could not find any documentation for the same and wanted to know if it is possible,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.