I have a mongodb database where I saved raw html in it. I have created a custom attribute in the html called kk-id to mention objects inside the html. I want to replace that particular html tag with an anchor tag.
I figured a way to do it using vanilla javascript, however I was wondering if there was a more efficient reactjs way to do it.
data example
<p>Hello <span kk-id="123">John Doe</span></p>
where John Doe's id is 123 saved in it.
/// react component
import React, { useEffect, useState } from "react";
export default function TestComponent() {
const [html, setHtml] = useState(
`<p>Hello <span kk-id="123">John Doe</span><br /></p>`
);
useEffect(() => {
const span = document.querySelector(`[kk-id]`);
if (span) {
const a = document.createElement("a");
a.href = "/people/john-doe";
a.innerText = span.innerText;
span.parentNode.replaceChild(a, span);
}
}, [html]);
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}