Home > OS >  ReactJS fetched html data manupilation
ReactJS fetched html data manupilation

Time:08-25

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 }} />;
}

CodePudding user response:

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.

CodePudding user response:

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>
        }
    }
});
  • Related