unairoldan
unairoldan

Reputation: 2863

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?

Upvotes: 3

Views: 5328

Answers (3)

Juan Marco
Juan Marco

Reputation: 3241

Another possible alternative would be to use the utility React HTML Parser which can convert HTML strings into react components (JSX).

Building on the example provided by Dennis:

import React from "react";
import ReactHtmlParser from "react-html-parser";

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" })
);

export default function App() {
  return <div>{ReactHtmlParser(htmlcontent)}</div>;
}

Working example

Upvotes: 0

Mudasir Zahoor
Mudasir Zahoor

Reputation: 914

I don't know what use case are you trying to solve using this but you can edit your shareThis function like this to return html as a string to use it as innerHtml later:

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

This should work..

Upvotes: 0

Dennis Vash
Dennis Vash

Reputation: 53884

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

Upvotes: 2

Related Questions