Note: The React example cannot be run directly in the browser like the other HTML examples. It requires a build step to compile the JSX code.
Project Structure & Code
Explore the key files needed to integrate OMD into a React application.
src/App.jsx
import { useEffect, useRef } from 'react';
import { omdDisplay, omdNumberLine } from '@teachinglab/omd';
function App() {
const equationRef = useRef(null);
const numberLineRef = useRef(null);
useEffect(() => {
// 1. Render an Equation
// We use a ref to tell OMD where to mount the SVG
const display = new omdDisplay(equationRef.current);
display.render("x^2 + 3x + 2 = 0");
// 2. Create and Render a Visualization (Number Line)
const numberLine = new omdNumberLine();
numberLine.loadFromJSON({
min: -5,
max: 10,
dotValues: [4]
});
const numberLineDisplay = new omdDisplay(numberLineRef.current);
numberLineDisplay.load(numberLine);
// Example: Updating the visualization dynamically
// numberLine.addNumberDot(7);
// numberLineDisplay.load(numberLine);
}, []);
return (
<div style={{ padding: '2rem' }}>
<h1>OMD React Demo</h1>
<div ref={equationRef}></div>
<div ref={numberLineRef} style={{ marginTop: '2rem' }}></div>
</div>
);
}
export default App;
src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
optimizeDeps: {
// Ensure mathjs and openai are pre-bundled if needed
include: ['mathjs', 'openai'],
// Exclude OMD from optimization to ensure proper loading of its internal modules
exclude: ['@teachinglab/omd', '@teachinglab/jsvg']
}
});
package.json
{
"name": "react-demo",
"version": "1.0.0",
"type": "module",
"dependencies": {
"@teachinglab/jsvg": "^0.1.1",
"@teachinglab/omd": "^0.6.6",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.2.1",
"vite": "^5.0.0"
}
}
How to Run
To run the React demo, you need to start the development server using Node.js.
1. Open a Terminal
Navigate to the react-demo directory:
cd react-demo
2. Install Dependencies
npm install
3. Start the Server
npm run dev
Once the server starts, open the URL shown in the terminal (usually http://localhost:5173).
Why is this necessary?
React uses JSX (JavaScript XML) to write HTML-like syntax in JavaScript. Browsers cannot understand JSX directly; it must be "transpiled" into standard JavaScript using a tool like Vite or Webpack.
The other examples in this library use standard HTML and JavaScript modules, which modern browsers can run natively.