I would like to know how can I inject dynamically component from text with html and execute it.
I would like, for example, replace <abbr></abbr>
by a custom component.
Currently, I have a text:
<h1>Lorem</h1> ipsum <abbr title="">Test1</abbr> dolor sit amet <abbr title="">Test2</abbr> lorem ipsum <abbr title="">Test3</abbr>.
I would like to inject a CustomComponent to replace <abbr></abbr>
:
let injectComponent = (text) => {
let replacedText;
const regex = /<abbr title="">(.*?)</abbr>/g;
replacedText = text.replace(regex,function(_,match) {
return `<CustomComponent data="${match}" />`
})
return replacedText;
}
And I use injectComponent in:
<span className="text-slate-900"
dangerouslySetInnerHTML={{ __html: injectComponent(post.content) }}>
</span>
But the CustomComponent is not render. In the dom, there is customcomponent and it’s not show on the front.
2
Answers
Please see my solution below. I hope it helps you.
I noticed an error in this code.
CustomComponent is being converted to string. React does not recognize it as a React Element. React only supports html elements so
<CustomComponent data="${match}" />
will not work like you thought.Code Sandbox
In React, you can use the dangerouslySetInnerHTML attribute to dynamically inject HTML code, and use a custom component to replace the tag with your desired component.
With these steps, you can dynamically inject HTML code with React and replace the tag with your custom component. When the MyComponent component is rendered, the HTML code is injected and the tag is replaced with your custom component, which can be executed and displayed in the browser.