Yogesh Chavan’s Post

Do you know that, you can't render HTML in React using JSX? If you've ever tried doing something like this in React: const html = "<p>This is <strong>HTML</strong></p>"; <div>{html}</div> You’ll notice it just renders as plain text with tags displayed as it is. Because React escapes everything inside JSX by default for security reason. ✅ This prevents malicious code from running, and that's a good thing! But what if you actually need to render HTML coming from an API? then you need to write it like this: <div dangerouslySetInnerHTML={{ __html: html }} /> React has provided a prop with name of dangerouslySetInnerHTML where you can specify the html that you want to render. But as the prop name suggests, it's dangerous if not handled properly ❌ The html string might contain malicious script or code that can cause XSS attack, might read your cookies or do some other harm. So never use this way to render html content as a string. ✅ Best Practice: Combine These Two Tools Use DOMPurify and html-react-parser npm packages. → DOMPurify – Sanitizes HTML before rendering (removes all the XSS and dangerous script/html code) → html-react-parser – Converts sanitized HTML into real React components import DOMPurify from 'dompurify'; import parse from 'html-react-parser'; const cleanHTML = DOMPurify.sanitize(htmlString); <div>{parse(cleanHTML)}</div> ✨ This keeps your app secure while still letting you render dynamic HTML safely. TL;DR: ✅ You can't render HTML directly in JSX, and that’s a good thing. ✅ Use DOMPurify + html-react-parser combo instead of dangerouslySetInnerHTML. ✅ Always sanitize user-generated or untrusted content. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories