How to avoid html escaping of text children when calling React.createElement?

Estimated read time 2 min read

When you use React.createElement to create a React element with text children, the text is automatically escaped to prevent XSS attacks. However, there are times when you may want to render raw HTML in your component’s text content without being escaped.

To avoid HTML escaping of text children when calling React.createElement, you can use the dangerouslySetInnerHTML prop. Here’s how to do it:

const text = '<strong>Hello world!</strong>';
const element = React.createElement('div', {
  dangerouslySetInnerHTML: { __html: text }
});

ReactDOM.render(element, document.getElementById('root'));

In this example, we’re creating a div element with the dangerouslySetInnerHTML prop set to an object with a single property __html, whose value is the raw HTML that we want to render.

Note that using dangerouslySetInnerHTML can be dangerous if you’re not careful, as it can open your app up to XSS attacks if you’re not sanitizing the HTML content that you’re rendering. Make sure to properly sanitize any user-generated content before using it in this way.

Also note that it’s generally better to use React’s built-in mechanisms for rendering text content instead of relying on dangerouslySetInnerHTML. However, in certain cases, such as when you need to render third-party HTML content, dangerouslySetInnerHTML can be a useful tool.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply