I have found similar to my issue here .
But I have a little bit different scenario. I have string of html rather than just string. So, I wanted to do:
Let's suppose MyComponent is just returning h3 element for now:
const MyComponent = ({children}) => (<h3>{children}</h3>)
var parts = "<h1>I</h1><p>am a cow;</p>cows say moo. MOOOOO."
.split(/(\bmoo+\b)/gi);
for (var i = 1; i < parts.length; i += 2) {
parts[i] = <MyComponent key={i}>{parts[i]}</MyComponent>;
}
// But I need html to be rendered
return <div dangerouslySetInnerHTML={{ __html: parts }} />
This will be rendered in the browser like this:
I
am a cow;
cows say ,[object Object],. ,[object Object],.
What I can think here to resolve the issue is converting component with string of html first.
parts[i] = convertToStringOfHtml(<MyComponent key={i}>{parts[i]}</MyComponent>);
But I don't have idea how to convert component to string of html.
You can do with react-dom
import { renderToString } from 'react-dom/server'
//
//
parts[i] = renderToString(<MyComponent key={i}>{parts[i]}</MyComponent>)
view more here https://reactjs.org/docs/react-dom-server.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.