Reputation: 11
I have a database full of blog entries written over the past 26 years. The blog code is a php script that pulls entries from the db and includes them inline in the page it generates. I'm learning to use React now and one project is to write better code for the blog... It looks to me like the only way to use the db entries as they exist now, would be to dangerouslySetInnerHTML on the blog entry elements of the generated page. Is this correct? The db entries are guaranteed valid HTML but not valid XML, lots of unclosed tags...
Alternately: If I was writing a new application and wanted to allow a trusted user to write entries containing complex markup (i.e. stuff not supported in markdown like tables for example, even scripts), and then include the entries on a page, is there a good way to do this without using dangerouslySetInnerHTML? Is there a better format for storing the entries than as text with markup? And what if the user is not trusted, is there a good way to validate the entries and remove markup that looks dangerous?
I have not yet started to write code for this project. The code I am thinking of looks like
function BlogEntry({title, htmlData}) {
return <div>
<h1>title</h1>
<div dangerouslySetInnerHTML={{__html: htmlData}} />
</div>
}
But there's got to be a better way?
Upvotes: 1
Views: 21
Reputation: 13662
If you have existing HTML, dangerouslySetInnerHTML
is how you'd render it declaratively. Or, you could use an iframe
with a srcdoc
and use the sandbox
attribute to try to sandbox the content away from the main site.
As for allowing users to write formatted text, that question is very opinion-based, but one popular option is to use Markdown which you can render out without dangerouslySetInnerHTML with a library e.g. react-markdown or remark.
If you want to sanitize the HTML, try DomPurify.
Upvotes: 0