0

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 }} />;
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
ghophri
  • 183
  • 1
  • 1
  • 12

2 Answers2

1

You can use html-react-parser and just do

import parse from "html-react-parser";
...

const newParsedHtml = parse(html, {
    replace: ({attribs}) => {
        if (domNode.attribs && domNode.attribs.id === "123") {
            return <span>dynamic text here</span>
        }
    }
});
  • This solotion is ALMOST correct. `const options = { replace: (domNode) => { if (domNode.attribs?.kkid) { return {domNode.children[0].data}; } }, };` – ghophri Aug 25 '22 at 04:25
0

I hope vanilla js is the simplest way to do it. For enhancement purpose you can see this. it will be more readable and reusable.