Categories
React Answers

How to Render an HTML String within a React Component?

Spread the love

Sometimes, we want to render an HTML string in a React component.

In this article, we’ll look at how to render an HTML string in a React component.

Render an HTML String within a React Component with the dangerouslySetInnerHTML Prop

We can use the dangerouslySetInnerHTML prop to render an HTML string onto the screen.

For instance, we can write:

import React from "react";

export default function App() {
  const articleContent = "<p><b>Lorem ipsum dolor laboriosam.</b></p>";

  return (
    <div className="App">
      <div dangerouslySetInnerHTML={{ __html: articleContent }} />
    </div>
  );
}

to add the dangerouslySetInnerHTML with an object with the __html property set to the articleContent HTML string as its value.

Then we see the HTML rendered as is without escaping.

Conclusion

We can use the dangerouslySetInnerHTML prop to render an HTML string onto the screen.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *