javascripthtmlreactjshtml-rendering

How to render html from a string in a database


I am wanting to create a blog, this blog is for me to record my journey learning to become a software engineer/web developer. I have a separate offline blog uploader where I will create a title and the content and upload it to a database this has two inputs.

1.title

2.post_text

. However I want my blog posts to be able to render custom html for example the output from the database is this title: Test, post_text:<h1>This is a test!</h1>

However I have no clue how to render this HTML.I tried using createElement() and. then adding that to the DOM however that wasn't working First step is displaying it on the 'all posts' section in mini cards. Next would be creating the page that will render this detail.

I am using React.js for the blog. Can anyone link me to some help, or can anyone suggest any ideas I could to tackle this issue


Solution

  • React has dangerouslySetInnerHTML for exactly this. If you're receiving HTML and you want it to be rendered as HTML (not as a string):

    <div dangerouslySetInnerHTML={{ __html: post_text }} />
    

    You should make sure your HTML is coming from a trusted source - in your case, a CMS should be fine.