default vs named export
JavaScript React
default vs named export
dangerouslySetInnerHTML
is a React property that allows you to directly inject HTML content into a DOM element. It's essentially React's replacement for using innerHTML in regular JavaScript.
function MyComponent() {
const htmlContent = {
__html: '<p>This is <strong>HTML</strong> content</p>',
};
return <div dangerouslySetInnerHTML={htmlContent} />;
}
It's considered dangerous for several reasons:
- Cross-Site Scripting (XSS) Vulnerability: If you inject user-provided HTML content without proper sanitization, malicious users could inject JavaScript code that executes in your application's context.
// Dangerous! Never do this with user inputconst userInput ='<img src="x" onerror="alert(\'hacked!\')" />';<div dangerouslySetInnerHTML={{ __html: userInput }} />;
- Breaking React's Virtual DOM: React maintains a virtual DOM to efficiently update the actual DOM. When you use dangerouslySetInnerHTML, you're bypassing React's normal flow and directly manipulating the DOM, which can lead to inconsistencies.
Instead of using dangerouslySetInnerHTML, you should:
- Use React's built-in JSX syntax whenever possible
- If you must render HTML strings, use a trusted HTML sanitization library like DOMPurify
If you absolutely must use dangerouslySetInnerHTML (for example, when working with a CMS that provides HTML content), always sanitize the input first as shown below.
import DOMPurify from 'dompurify';
function SaferHtmlRenderer({ htmlContent }) {
const sanitizedContent = {
__html: DOMPurify.sanitize(htmlContent),
};
return <div dangerouslySetInnerHTML={sanitizedContent} />;
}
00:00