Sometimes, we want to convert HTML Strings to JSX with React.
In this article, we’ll look at how to convert HTML Strings to JSX with React.
Convert HTML Strings to JSX with React
There’re several ways to convert HTML Strings to JSX with React.
One way is to put the string in between curly braces in our component.
For instance, we can write:
import React from "react";
export default function App() {
return <div>{"First Second"}</div>;
}
to put a string in between the curly braces to render it.
Another way is to put the string in an array with other strings or JSX code.
For instance, we can write:
import React from "react";
export default function App() {
return <div>{["First ", <span key="1">·</span>, " Second"]}</div>;
}
We add the span
element as the 2nd element between 2 strings.
Any element or component should have a key
prop, so we set the key
prop of the span so React can keep track of it.
Finally, we can use the dangerouslySetInnerHTML
prop render an HTML string as HTML in our component:
import React from "react";
export default function App() {
return <div dangerouslySetInnerHTML={{ __html: "First · Second" }} />;
}
We pass in an object with the __html
property containing the text to render it.
Conclusion
There’re several ways to convert HTML Strings to JSX with React.
One way is to put the string in between curly braces in our component.
Another way is to put the string in an array with other strings or JSX code.
Finally, we can use the dangerouslySetInnerHTML
prop render an HTML string as HTML in our component.