I have strings stored in a DB that are partial HTML, for example:
“Intro<br /><br />Paragraph 1<br /><br />Paragraph 2”
Say I want to render this string within a new <p>
element, what is a simple way to accomplish this?
I am looking for a solution that doesn’t use an additional package and instead uses native JavaScript or a non-deprecated React function.
I am serving these string snippets to the React client, and I want React to eventually convert them from strings to HTML elements. However, doing so using document.createElement
and manipulating the innerHTML
of this new element gives me an error saying that Objects cannot be rendered in React. Say this new element is called elem
, I am trying to render is like so:
render(<div>{elem}</div>)
2
Answers
You can render it through this method:
Another way in React
The issue is that the string
“Intro<br /><br />Paragraph 1<br /><br />Paragraph 2”
is a string. It is not JSX. It does not get transposed into function calls for React elements. So that string will simply be output to the DOM as a string, and that string will appear as text in the browser.React uses a transpiling process to convert the JSX in your source code into JS function calls. It does that during build-time. The string in your database is not fetched until run-time, so there’s no opportunity for the React build process to transpile it.
Lots of people have done things to "make this work" at runtime, but mostly those solutions are clunky and/or extremely dangerous, security-wise.
For example: Programmatically generated JSX string
IMO the better approach would be for you to build some type of parser and/or simple Domain Specific Language (DSL) so that in your React code you are getting the data from the database, "interpreting" it, and dynamically rendering JSX.
For example, the above string could be processed as: