Anil Sharma
Anil Sharma

Reputation: 285

What is correct way of passing html tags in React State?

I am in process of creating Blog using React. I am planning to bring main content of blog from server and passed to React Component via Props/State. Blog content can have html tags like :

I was hoping to store content of blog in Database/json files along with these tags and render the content as it is on page load. But It seems to be difficult to do it in React. There are three ways we can achieve this :

  1. dangerouslySetInnerHTML
  2. Storing content in form array object [html content] ( pushing a String content to array won't work ).
  3. Passing unicode characters for all html entities.

This Question discuss these approaches pretty well :

Rendering raw html with reactjs

My Queries are :

  1. Should there be change in over all flow/architecture to handle this?
  2. What is best way to insert large html content from ajax call to react component to render ?
  3. What design decisions should be considered to make fully functional and dynamic/scalable Blog ?
  4. How to get SEO on your dynamic content like blog content ( which is stored in some file/database ). ?

Upvotes: 2

Views: 2904

Answers (1)

Hugo Silva
Hugo Silva

Reputation: 6948

There is nothing special about dangerouslySetInnerHTML. Rendering HTML from javascript could always be dangerous, regardless of using React or not, depending on the source of said HTML. For example, if you are rendering a post that you created yourself, and saved to a database, then there is no danger (unless your database has been compromised). But let's say you have comments on a post, and an user sends malicious code as a comment. All other users accessing that page, would fetch the malicious code from the database, and "dangerously" execute it on their browsers. So, what you need to do, is make sure the source of HTML is secure, by sanitizing any user input BEFORE saving to the database. There are libraries you can use to achieve that, example - http://htmlpurifier.org/

Regarding SEO, you can use server side rendering - https://www.smashingmagazine.com/2016/03/server-side-rendering-react-node-express/

Make sure you have all the information you need available on the url, so you don't rely on "state" to render a page, like post id, etc. You can achieve that by using React Router - https://github.com/reactjs/react-router

Upvotes: 4

Related Questions