Git Product home page Git Product logo

react-mathjax-preview's Introduction

react-mathjax-preview

Travis npm package

react-mathjax-preview provides one React component to render MathML, TeX or ASCIImath formulas. See demo.

Installation

Install react-mathjax-preview as a dependency:

yarn add react-mathjax-preview

Usage

Import the package and fill the math property with some text containing your formals. Wrap TeX in $ or $$ and ASCIImath in `. Paste MathML as is.

import React, {Component} from 'react'
import {render} from 'react-dom'
import MathJax from 'react-mathjax-preview'

const asciimath = '`sum_(i=1)^n i^3=((n(n+1))/2)^2`' # Because of the backtick
const math = String.raw`
  <math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
    <menclose notation="circle box">
      <mi> x </mi><mo> + </mo><mi> y </mi>
    </menclose>
  </math>

  $$\lim_{x \to \infty} \exp(-x) = 0$$

  ${asciimath}`

class Demo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      math: tex
    }
  render() {
    return <MathJax math={this.state.math} />
  }
}

Props

className

Wrapper classname

id

Wrapper id

style

Style object

wrapperTag

Wrapper tag, "div" is default

math

MathJax content

msDelayDisplay

Milliseconds to delay display of div, 300 is default

onDisplay (Function)

Triggered after delay and div is shown, hopefully typeset has finished

config (Object)

MathJax configuration

onLoad (Function)

Triggered after MathJax script finishes loading before children are allowed to render.

onError (Function)

Triggered when any Math Processing Error occurs

sanitizeOptions

DOMPurify configuration object (optional). See https://github.com/cure53/DOMPurify#can-i-configure-dompurify

Development

Clone the repo and run yarn commands available in the package.json file.

$ git clone https://github.com/mehdisadeghi/react-mathjax-preview && cd react-mathjax-preview
$ yarn install // install dependencies
$ yarn start // start the development server which serves the demo page
$ yarn build // make a production build inside the dist folder
$ yarn build:demo // make a demo build inside the dist folder

And browse to localhost:3000.

License

MIT

react-mathjax-preview's People

Contributors

ahamelers avatar bertrand-riviere avatar cmdr3nder avatar dependabot[bot] avatar dpikt avatar lionelb avatar mehdisadeghi avatar mikesha avatar nkrmr avatar nwheatle avatar reddine avatar renovate-bot avatar svgpubs avatar udit-compro avatar zaynex 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

Watchers

 avatar  avatar  avatar  avatar

react-mathjax-preview's Issues

Default Sanitize create problems with normal html

Scenerio : The math string that we pass to component not necessarily contains the TEX or math ascii etc, it may contains simple HTML too. e.g.

const math = "<p>N<sub>2</sub>O<sub>3</sub></p>";

Expectation is , component should convert the math expression and leave rest as it is. but the default sanitization setting that are added 2.2.0 onwards remove the html tag.

e.g.
const defaultSanitizeOptions = {
USE_PROFILES: {mathMl: true},
ADD_ATTR: ['columnalign'],
}

DOMPurify.sanitize(math, {...defaultSanitizeOptions});

Convert above expression to N2O3 and we loss html tag and hence parsing..

please remove the default sanitisation..

Type of propTypes.style should be object

Passing an object into the default component causes a warning in Chrome DevTools. Passing a string into the react-mathjax-preview div causes a Javascript error. Changing the type of propTypes.style to PropTypes.object will eliminate the warning.

In demo/src/index.js, line 118, style is passed in as an object:
<Example math={this.state.math} style={{marginTop: '20px'}}/>

The warning from Chrome DevTools: Warning: Failed prop type: Invalid prop style of type object supplied to _class, expected string.

Integrate with jsx MathML

In React it's possible to return MathML from a jsx function like:

import React from 'react';

function oneThird() {
  return (
    <math>
      <mfrac>
        <mn>1</mn>
        <mn>3</mn>
      </mfrac>
    </math>
  );
}

Is it possible to integrate this with the <MathJax /> component?

My current work-around is to convert the MathML to a string with ReactDOMServer.renderToString():

render() {
  <MathJax math={ReactDOMServer.renderToString(oneThird())} />;
}

Issue with NPM Install due to dependency issue

In my project, I am facing this issue

D:\review\project>npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! dev react@"^17.0.2" from the root project
npm ERR! peer react@"^16" from [email protected]
npm ERR! node_modules/react-mathjax-preview
npm ERR! dev react-mathjax-preview@"^2.2.4" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Error on setting 'loading: true' state

Hi, I'm getting an error while initial loading a page with react-mathjax-preview. The error message:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the _default component.

It refers to the line https://github.com/mehdisadeghi/react-mathjax-preview/blob/master/src/index.js#L28

Here is my component code, where I use mathjax:

import React, { Component } from "react";
import MathJax from "react-mathjax-preview";

import "./index.css";

class XMarkdown extends Component {
  constructor(props) {
    super(props);
    const {
      data,
      question
    } = props;
    this.state = {
      source: data.text ? data.text : question;
    };
  }
  render() {
    return <MathJax math={this.state.source} />;
  }
}

export default XMarkdown;

Flickering When Rendering

Hi,

I am using react-mathjax-preview for rendering math-ml formulas. Everything works fine, but the initial rendering is flickering. For example, I am receiving this Math-ML formula:

<math> <mtext>V =</mtext> <mfrac> <mtext>&#x3C0; . r . v</mtext> <mtext>3</mtext> </mfrac> <mtext/> </math>

Then this string is used with mathjax-preview like this:
<MathJax math={formula.Value} />

At the beginning, everything is drawn in one line and no fraction is displayed. Then the number "3" moves to the denominator and the fraction is displayed. In last step size and padding is adjusted. This all takes about 0.5 - 1.0 second and the user sees the flickering and rearrangement of the entire form.
Can you please help me with this issue? Is it possible something like "generate formula in the background" and "then draw final formula to the screen"? Something like callback method, which will tell me that the formula is generated and should be displayed?

Thank you!

Screen readers don't announce exponents correctly

Currently, when a screen reader (specifically Mac VoiceOver, but maybe others too) reads out an equation that contains exponents, it doesn't properly announce the exponents. In the example screenshot, it simply reads out "cos two theta minus sin two theta" where both of the twos are supposed to be exponents.

Is there any way to address this?

Screen Shot 2020-03-23 at 10 42 32 AM

Edit: forgot to add screenshot

Line wrapping Doesn't working

After added "HTML-CSS": { linebreaks: { automatic: true } in config, its working properly ( text-wrap) only when i refresh each time. while doing normal component shift (one component to another component) navigation line-break is not getting applied. Could any one please help me to fix this.

Here are the details:

Markup:

let config = { "HTML-CSS": { linebreaks: { automatic: true }, width: "container" } }

Plugin Version :
2.2.3

MathML Tag:
<MathJax config={config} ....

MathML sample questions

Application Output
preview2

Preview Link Output
reactPreview

No files in package 1.0.0

Hi,

First of all, thanks for this package !

I tried to use the 1.0.0 version but all I got in the package was this:

Screenshot 2020-02-26 at 16 59 50

Did you build the lib and esfolder before publishing ? Not sure what's wrong but 1.0.0 cannot be imported in my project for sure :(

Error when rendering formulas in Firefox browser

Hi there.

I am using react-mathjax-preview component to draw some formulas in html pages but, unfortunatelly, I found some problems specifically when rendering them at Firefox browser. There are two errors:

  • first to pop

window.chrome is undefined

  • second to pop

this.queue is undefined

The second error is catched and displayed on screen by Error Boundaries (I guess they may be related), as the image bellow shows

image

But it works totally fine in Chrome/Edge

image

I'm using React 17 and react-mathjax-preview 2.2.6, nothing exceptional. Code as example:

...
  <MathJax
	  math={
		`\`${' ... '}\``
	  }
	  msDelayDisplay={ mathJaxMsDelayedDisplay }
  />
...

Thank's for any help! Regards.

Component is susceptible to XSS

I was using this component to render some user input- I didn't realize it was using innerHTML under the hood ๐Ÿ˜ฑ

For example, you can enter the following into the demo:

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" onload="document.body.style.backgroundColor = 'red';alert('Im a bunch of arbitrary javascript!!!');">

This is bad news.

I'm not sure if there's a way around this with the way this component currently renders Mathjax, but it should certainly be documented if it's a necessary consideration in using the component.

TypeError:_dompurify.default.sanitize is not a function

Hi

I am trying it implement MathJax on my website using react-mathjax-preview Component. it is working fine on Client side rendering but on server-side I am getting this error.

I am using Next.js for SSR.

Please help to solve this.

Screenshot 2021-08-10 at 1 36 41 PM

React: 16.13.1
react-mathjax-preview: 2.2.3
NextJs: 9.5.2

Unexpected text node: '2', can't use annotation tags

<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>=</mo><semantics><mrow><mn>2</mn></mrow><annotation encoding="text/plain">2</annotation></semantics><mspace linebreak="newline"/><mn>2</mn><mo>=</mo><semantics><mrow><mn>3</mn></mrow><annotation encoding="text/plain">3</annotation></semantics></math>

I tried this math formula here, https://focused-tesla-b6fe0a.netlify.com/, and It shows Unexpected text node: '2'.
But when I delete all the annotation tags it works?

Broken rendering on component update

We discovered a bug that prevents proper LaTeX formula re-rendering if the formula changes.

How to reproduce (Google Chrome):

  1. Open https://mehdisadeghi.github.io/react-mathjax-preview/
  2. Copy and paste this LaTeX: $$ \begin{equation} \label{eq1} \begin{split} A & = \frac{\pi r^2}{2} \\ & = \frac{1}{2} \pi r^2 \end{split} \end{equation} $$
  3. Append any text in the editor.
  4. The formula rendering breaks. It shows a box with LaTeX code.

Use latest MathJax 2.7.x

So I noticed that MathJax has had several releases since 2.7.0.

I suggest updating to 2.7.6 since 3.0 might have large changes to avoid with it only being 7 days old at the time of writing.

Is there a reason not to update to 2.7.6 I haven't discovered?

allow to configure root tags rendered by MathJaxPreview

hello,
first, thanks for this nice component, it is very useful!

i ran into an issue because i need to render MathJax components inside <p> elements (and i cannot change that); this causes an annoying React warning: "Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>."
(+ this warning actually makes sense since it is not semantically correct to put <div> inside <p>)

i wondered if you would accept a PR that allows to configure the tag, ex:
React.createElement(tag, ...) where "tag" is a new prop of MathJaxPreview instead of the "hardcoded" <div> s that are actually rendered?
by having a defaultProps for "tag" of 'div', the behaviour would remain the same than today and i (+ others) could use this new props to avoid similar problems.

MathJax Has Lots of delays

I have some lines and formulas but it takes long time to convert to formula like 20 seconds

this is the code

 questions.map((question,index)=>(
                            <div key={index}>
                                
                                    <h3>{index+1}- <MathJax sanitizeOptions={ {USE_PROFILES: {html: true,mathMl: true}}} style={{'display':'inline-block'}} math={question.title}  /></h3>
                                    <ul>
                                        {
                                            question.options.map(option=>(
                                                <li key={option.value} > <MathJax sanitizeOptions={ {USE_PROFILES: {html: true,mathMl: true}}} style={{'display':'inline-block'}}  math={option.label} /></li>
                                            ))
                                        }
                                    </ul>
                                
                            </div>
                        ))

Render problem in the React app

in the react app, when I change the router to a new page which includes Latex, It doesn't work. I have to refresh the page manually and then it works.
firstly:
image
image

Dynamic script URL

Hello,

Is it possible to set dynamically the script URL due to SCP issue?
Maybe we can define a props "script" into the component to set a default path to MatJax script.

Best regards,

Iframe is not displayed

<h3 dir="ltr">Watch This Video About Raising Anorexia Awareness:</h3>

<p><iframe allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/aTIjRxT_Y9g" width="560"></iframe></p>

This snippet code doesn't show the video in the iframe, tested in https://focused-tesla-b6fe0a.netlify.com/.
However it works as expected in online html editors, https://html-online.com/editor/.

Know All Mathjax loaded or not

I need to display a lot of questions which includes math jax equations, how to know whether all math jax content loaded or not, Please let me know how to do that

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.