Next.js Discord

Discord Forum

How do I show HTML from string in a div properly?

Unanswered
Chinese Alligator posted this in #help-forum
Open in Discord
Chinese AlligatorOP
I need to show some HTML (created from a editor and stored into database) in the page now. How do I do that? is dangerouslySetInnerHTML the more "elegant" way to do that?

5 Replies

That is the most common and easiest way. Depending on your use case and time available, a library like this is probably the most elegant solution: https://www.npmjs.com/package/html-react-parser

There are a few different ones out that but they essentially convert html string to full react objects and allow for you to write in your own customizations. Some people have written parsers specific to various CMSs too, like WordPress.
@andrewscofield That is the most common and easiest way. Depending on your use case and time available, a library like this is probably the most elegant solution: https://www.npmjs.com/package/html-react-parser There are a few different ones out that but they essentially convert html string to full react objects and allow for you to write in your own customizations. Some people have written parsers specific to various CMSs too, like WordPress.
Chinese AlligatorOP
i'm trying to make it work with parser from html-react-parser module but what i'm getting the error:

Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.

Warning: Expected server HTML to contain a matching <p> in <p>.

See more info here: https://nextjs.org/docs/messages/react-hydration-error


i'm using getServerSideProps in this page since i read stuff from database into the component. my code goes as following: https://pastebin.com/4JTsXk3N and the component that uses parser: https://pastebin.com/WWXCnDAr where article.contents hold a string with the HTML
From the looks of that error, parser might not be running on the server. You might need to ask them about getting it to render on server or find a library/package that does. Or to test this out, you can dynamically load <ArticleBox> using next/dynamic with the ssr: false option added to it. This will delay the rendering of the article until the client. Not ideal, but at least that will narrorw down to see if thats the issue.
Jumbo flying squid
If you are sure that there is no malicious content in the HTML then dangerouslySetInnerHTML is the way to go.