How to Render HTML String in React Safely and Easily
In React, you can render an HTML string by using the
dangerouslySetInnerHTML attribute on an element. This attribute takes an object with a __html property containing your HTML string, allowing React to insert raw HTML safely.Syntax
Use the dangerouslySetInnerHTML attribute on a React element. It expects an object with a __html key holding the HTML string you want to render.
This tells React to insert the HTML directly inside the element instead of rendering it as plain text.
jsx
const htmlString = '<p>Hello <strong>World</strong>!</p>'; function MyComponent() { return <div dangerouslySetInnerHTML={{ __html: htmlString }}></div>; }
Output
<div>Hello <strong>World</strong>!</div>
Example
This example shows a React component rendering a simple HTML string with bold text inside a paragraph.
jsx
import React from 'react'; const htmlString = '<p>This is <em>italic</em> and this is <strong>bold</strong>.</p>'; export default function RenderHtml() { return ( <div> <h2>Rendered HTML String:</h2> <div dangerouslySetInnerHTML={{ __html: htmlString }}></div> </div> ); }
Output
<h2>Rendered HTML String:</h2>
<div>This is <em>italic</em> and this is <strong>bold</strong>.</div>
Common Pitfalls
- Security risk: Using
dangerouslySetInnerHTMLcan expose your app to cross-site scripting (XSS) attacks if the HTML string is from an untrusted source. - Do not use innerHTML directly: React does not allow setting HTML directly on elements except via
dangerouslySetInnerHTML. - Always sanitize: Sanitize any HTML string from users or external sources before rendering.
jsx
/* Wrong way: This will not render HTML tags, just show them as text */ const htmlString = '<b>Bold Text</b>'; function Wrong() { return <div>{htmlString}</div>; } /* Right way: Use dangerouslySetInnerHTML */ function Right() { return <div dangerouslySetInnerHTML={{ __html: htmlString }}></div>; }
Output
<div><b>Bold Text</b></div>
Quick Reference
| Concept | Description |
|---|---|
| dangerouslySetInnerHTML | React attribute to insert raw HTML inside an element |
| __html | Key in the object passed to dangerouslySetInnerHTML holding the HTML string |
| Sanitize HTML | Always clean HTML strings from untrusted sources to prevent XSS |
| No direct innerHTML | React does not support setting innerHTML directly on elements |
| Use JSX normally | For static content, prefer JSX tags instead of HTML strings |
Key Takeaways
Use dangerouslySetInnerHTML with an object containing __html to render HTML strings in React.
Never insert raw HTML from untrusted sources without sanitizing to avoid security risks.
Rendering HTML strings directly as children will show the tags as text, not HTML.
React requires this special attribute because it escapes content by default for safety.
Prefer JSX for static content and only use HTML strings when necessary.