1

I'm making a react application that has a blogging function and I need it to properly display my HTML content stored in my javascript object. This is what I mean:

const blog = {
  name: "post1",
  content: "<p>This is my first blog post</p>",
}

I have an object that stores the blog content and when I make a reference to the object I need it to render properly in the DOM as a paragraph, but instead, it renders with the tags displaying in react, please how do i fix it and make the content render as a DOM element

shadrack
  • 11
  • 2
  • 1
    See this post: https://stackoverflow.com/questions/19266197/reactjs-convert-html-string-to-jsx – jpthesolver2 Jun 03 '20 at 20:09
  • 1
    assuming you're using JSX in the rest of your app, just use that here instead of a string: `content: (

    This is my first blog post

    )`. This will be transpiled into a JS object (the output of `React.createElement`), rather than the string you now have.
    – Robin Zigmond Jun 03 '20 at 20:10
  • DangerouslySetInnerHTML works perfectly...thanks alot – shadrack Jun 04 '20 at 14:00

1 Answers1

1

You might use the dangerouslySetInnerHTML prop on a host component like a div:

<div dangerouslySetInnerHTML={ { __html: blog.content } } />

See also: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

0xc14m1z
  • 3,675
  • 1
  • 14
  • 23