Skip to content

Instantly share code, notes, and snippets.

@MohitSharma0101
Created May 9, 2024 14:38
Show Gist options
  • Save MohitSharma0101/44924d1fed1082842cf8220f4880c50a to your computer and use it in GitHub Desktop.
Save MohitSharma0101/44924d1fed1082842cf8220f4880c50a to your computer and use it in GitHub Desktop.
Add React Component in html string using parser
import parse, { Element } from "html-react-parser";
import { TestCard } from "./test-card";
function addTestCard(html: string): string {
// Define a regular expression pattern to match [template id="some-id-in-number"]
const templateRegex = /\[template id="(\d+)"]/g;
const replacedHTML = html.replace(templateRegex, (match, id) => {
return `<div id="test_card" tag=${id} />`;
});
return replacedHTML;
}
export const getHTMLWithAllCards = (
content: string = "",
) => {
let updatedHTML = addTestCard(content);
return parse(updatedHTML, {
replace(domNode) {
const attr = (domNode as Element).attribs;
if (!attr) return null;
if (attr.id === "test_card" && attr.tag) {
return <TestCard id={attr.tag} />;
}
},
});
};
const ContentSection = ({ content = "" }) => {
const htmlWithCardJSX = getHTMLWithAllCards(content);
return <div>{htmlWithCardJSX}</div>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment