In the world of web development, presenting content in an engaging and formatted way is crucial. However, when dealing with raw HTML content, traditional rendering methods might fall short. This is where React’s dangerouslySetInnerHTML comes into play. In this blog post, we’ll explore what dangerouslySetInnerHTML is and how to leverage it in your React applications, specifically focusing on a scenario involving Optimizely SaaS Core integration.
Understanding dangerouslySetInnerHTML
So, what exactly is dangerouslySetInnerHTML? In React, it’s a property that allows you to insert raw HTML into a component. The name itself suggests a certain level of caution because using it improperly can expose your application to potential security risks. However, when used judiciously, it can be a powerful tool for injecting HTML content into your components.
The Problem Statement
Let’s dive into a practical scenario. In a recent blog post on Optimizely SaaS and Next.js integration (you can find the post here), you might have noticed that the description field was displaying HTML elements. This can be undesirable as raw HTML tags might not provide the best user experience.

The Solution: dangerouslySetInnerHTML
To address this issue, we turn to dangerouslySetInnerHTML. This method allows us to place HTML code inside a container object, providing more flexibility in formatting our content.
To implement dangerouslySetInnerHTML, you can follow the syntax below:
...
return (
<>
<h1 className="mb-4 text-4xl font-extrabold">{page.Title}</h1>
<p dangerouslySetInnerHTML={createMarkup(page.Description)} />
</>
);
}
function createMarkup(c) {
return { __html: c };
}
In this code, the createMarkup function generates an object with a property __html containing the desired HTML content. The component then uses dangerouslySetInnerHTML to render this HTML content.
Conclusion
In conclusion, dangerouslySetInnerHTML is a valuable tool in the React developer’s toolkit, enabling the seamless integration of HTML content into components. However, it should be used with caution, and developers should be aware of the potential security implications. When employed correctly, this method enhances the presentation of content, providing a more dynamic and engaging user experience.