Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert React component into a String variable with html content

I need to insert a React component into a String variable that contains html content. This variable will be render with dangerouslySetInnerHTML.

I replace my placeholder "!#ShareButton" with the content of my React component, but it renders [object Object] instead of the component itself

React component:

const ShareThis = ({ text }) => {
  return (
    <div class="one-line">{text}</div>
)}

export default ShareThis

var content (string variable with html content)

<p>Text 1</p>
!#ShareButton
<p>Text 2</p>

Page:

const htmlcontent = content.replace(/!#ShareThis/g,
  <ShareThis
    text="Hello"
  />)

return (
  <div dangerouslySetInnerHTML={{ __html: htmlcontent }} />
)

Result:

Text 1
[object Object]
Text 2

Do you know how to insert a React component into a String variable with html content?

like image 946
unairoldan Avatar asked Jun 17 '26 13:06

unairoldan


1 Answers

You can't render React component as innerHTML because its an object, don't confuse between JSX and HTML.

To solve it your need content to be a valid HTML.

Can be done by making ShareThis a function returning a valid HTML as a string:

const ShareThis = ({ text }) => {
  return `<div class="one-line">${text}</div>`;
};

const content = `
<p>Text 1</p>
!#ShareButton
<p>Text 2</p>
`;

const htmlcontent = content.replace(
  /!#ShareButton/g,
  ShareThis({ text: "Hello" })
);

const App = () => {
  return <div dangerouslySetInnerHTML={{ __html: htmlcontent }} />;
};

Note that you have a typo in regex expression: /!#ShareButton/

Edit green-sound-n5fvc

like image 161
Dennis Vash Avatar answered Jun 19 '26 03:06

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!