Created
May 9, 2024 14:38
-
-
Save MohitSharma0101/44924d1fed1082842cf8220f4880c50a to your computer and use it in GitHub Desktop.
Add React Component in html string using parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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