When a user designs something in CKEditor5, I save data in the database as a string. Sample string from database record:
<p>What is the result of following?</p><p><math xmlns="http://www.w3.org/1998/Math/MathML"><msqrt><mn>16</mn></msqrt><mo> </mo><mo>+</mo><mo> </mo><mfrac><mn>3</mn><mn>9</mn></mfrac><mo> </mo><mo>=</mo><mo> </mo><mo>?</mo></math></p>
My question is about rendering html. I could parse the whole html string using the 'html-react-parser' package perfectly if it doesn't include <math/> tags. It did not parse <math/> tags and people suggested the 'react-mathjax-preview' package.
But when I parsed the whole html string with that, it parsed perfectly but then other html tags created on CKEditor5 looked like plain text. So I decided to convert the string to html with "DomParser()" and then loop in its "childNodes" searching if it has a math tag. Then I parsed each one separately with (parse() or <MathJax/>)
import MathJax from 'react-mathjax-preview';
const MathjaxParser = ({ mString }) => {
return <MathJax id="math-preview" math={mString} />;
};
export default MathjaxParser;
.
import React from 'react';
import parse from 'html-react-parser';
import MathJax from 'app/components/MathjaxParser';
const Parser = ({ mString }) => {
const iparser = new DOMParser();
const parsedHtml = iparser.parseFromString(mString, 'text/html');
const itemsArray = [];
if (!parsedHtml || !parsedHtml.body) return null;
parsedHtml.body.childNodes.forEach(item => {
let type = 'normal';
if (!item.outerHTML) return;
if (item.outerHTML.includes('xmlns="http://www.w3.org/1998/Math/MathML')) {
type = 'math';
}
itemsArray.push({ type, html: item.outerHTML });
});
return (
<div className="cursor-pointer">
{itemsArray.map((item, index) =>
item.type === 'math' ? (
<MathJax key={index} mString={item.html} />
) : (
<div key={index}>{parse(item.html)}</div>
)
)}
</div>
);
};
export default Parser;
In anywhere of the project, I render it like:
import Parser from 'app/components/Parser';
..........
return ( <Parser mString={stringHTML} /> );
But I think it is a workaround and I would like to ask what is the correct way you suggest?