Display math in TeX with KaTeX and ReactJS
npm install react-katex  
> Display math expressions with KaTeX and React
``sh`
$ npm install react-katex
# or
$ yarn add react-katex
`jsx`
import 'katex/dist/katex.min.css';
import { InlineMath, BlockMath } from 'react-katex';
Display math in the middle of the text.
`jsx
var InlineMath = ReactKaTeX.InlineMath;
ReactDOM.render(
document.getElementById('math'));
// or
ReactDOM.render(
document.getElementById('math'));
`
It will be rendered like this:
Display math in a separated block, with larger font and symbols.
`jsx
var BlockMath = ReactKaTeX.BlockMath;
ReactDOM.render(
document.getElementById('math'));
// or
ReactDOM.render(
document.getElementById('math'));
`
It will be rendered like this:
Note:
Don't forget to import KaTeX CSS file.
`jsx`
import 'katex/dist/katex.min.css';
#### Default error message
By default the error rendering is handled by KaTeX. You can optionally pass errorColor (defaults to #cc0000) as a prop:
`jsx
var BlockMath = ReactKaTeX.BlockMath;
ReactDOM.render(
errorColor={'#cc0000'}
/>, document.getElementById('math'));
`
This will be rendered like so:
#### 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:
`jsx
var BlockMath = ReactKaTeX.BlockMath;
ReactDOM.render(
renderError={(error) => {
return Fail: {error.name}
}}
/>,
document.getElementById('math'));
// The code above will render 'Fail: ParseError' because it's the value returned from renderError.`
This will render Fail: ParseError:
In addition to using the math property, you can also quote as a child allowing the use of { } in your expression.
`jsx`
ReactDOM.render(
document.getElementById('math'));
Or Multiline
`jsx\\frac{\\text{m}}
ReactDOM.render(
{\\text{s}^2}},`
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.
`jsx\frac{\text{m}}{\text{s}^2}
ReactDOM.render(},`
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 \
``jsx","
const latex = (...a) => String.raw(...a).replace("\\")\`
ReactDOM.render(},`
document.getElementById('math'));
You can even do variable substitution
`jsx\frac{\text{${top}}}{\text{${bottom}}^2}
const top = "m";
const bottom = "s";
ReactDOM.render(},``
document.getElementById('math'));