DEV Community

Mulugeta Chernet
Mulugeta Chernet

Posted on

🐱‍👤Leveraging MathJax in React.js with CDN✨

Image description

Introduction:

MathJax is a JavaScript display engine for mathematics that works in all browsers. Integrating MathJax into a React.js application can be a game-changer for projects that involve mathematical expressions, equations, or any kind of mathematical notation. MathJax, a powerful JavaScript library, makes it easy to display mathematical content beautifully on the web. In this blog post, we'll explore how to seamlessly incorporate MathJax into your React.js application using a CDN (Content Delivery Network).

step 1: Install MathJax using CDN

In your public/index.html file, add the MathJax CDN link in the head section:

 <script type="text/javascript" async
      src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script id="MathJax-script" async
      src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
    </script>
Enter fullscreen mode Exit fullscreen mode

step 2: Create a Component for MathJax Rendering

In your src/components/MathJaxComponent.js:

import React, { useEffect } from 'react';

const MathJaxComponent = ({ mathExpression }) => {
  useEffect(() => {
    window.MathJax.typeset();
  }, [mathExpression]);

  return (
    <div>
      {mathExpression && (
        <span
          dangerouslySetInnerHTML={{ __html: mathExpression }}
        />
      )}
    </div>
  );
};

export default MathJaxComponent;

Enter fullscreen mode Exit fullscreen mode

Step 3: Use the MathJax Component in Your App

function App() {
  const mathExpression = '\\[x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}.\\]'; // Replace with your mathematical expression

  return (
    <div className="App">
      <h1>MathJax in React.js</h1>
      <MathJaxComponent mathExpression={mathExpression} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Conclusion:

By following these steps, you can seamlessly integrate MathJax into your React.js application using a CDN. Whether you're building an educational platform, a scientific tool, or any other project involving mathematical content, MathJax will elevate the quality and accessibility of your mathematical expressions on the web. Happy coding!

Top comments (0)