0

I receive html as a string from a CMS.

What I want to achieve, is replacing some of this content, with a React component

Example could be

const html = "<div class="example"><h1 class="title>Title</h1></div>"

Everytime the HTML string has the class "title" included, I want to replace the h1 element with <Title />

Example of component

const Title = () => {
 const [clicked, setClicked] = React.useState(false)
return <h1 onClick={() => setClicked(!clicked)} style={clicked ? {color: 'red'} : {color: 'blue'}>Title</h1>

Is this even possible?

jonask
  • 679
  • 2
  • 6
  • 21

1 Answers1

0

I recommend you using this library to convert string to html https://www.npmjs.com/package/react-html-parser if you need. if you want to change tagName to h1 when class="title", please do like this: Is it possible to change paragraph tag to header tag by using JavaScript?

const [clicked, setClicked] = React.useState(false)

function changeTagName(el, newTagName) {
    var n = document.createElement(newTagName);
    var attr = el.attributes;
    for (var i = 0, len = attr.length; i < len; ++i) {
        n.setAttribute(attr[i].name, attr[i].value);
    }
    n.innerHTML = el.innerHTML;
    n.onClick = () => {setClicked(!clicked)} style={clicked ? {color: 
    'red'} : {color: 'blue'}}
    el.parentNode.replaceChild(n, el);
}

changeTagName(document.getElementById('damn'), 'h1');
Cuong DaoVan
  • 262
  • 2
  • 6