String to HTML in React Js

Last updated : August 9, 2022

If you want to render HTML code stores as a string in a string variable, first, you have to convert that string to HTML. I discuss two ways to convert strings to HTML in this article.

  1. Using React's dangerouslySetInnerHTML
  2. Using html-react-parser npm package

Here is an example of what happens if I render HTML stored in a string variable. The content displays as it is. That is similar to Javascript's innerText method.

import { useEffect, useState } from "react";
export const StringToHtml = () =>{
  const [html, setHtml] = useState<string>("")
  useEffect(() => {
    setHtml("<div>Html stored as a string</div>")
  }, [html])
  return(
      <div>{html}</div>
  )
}
React render string html
Figure 1: React render string html

Using React's dangerouslySetInnerHTML

However, React Js does this on purpose. It prevents XSS (cross-site scripting). Therefore, React Js designers named the method that allows you to parse a string to HTML as dangerouslySetInnerHTML. Here is how to use it. Do not use dangerouslySetInnerHTML to render HTML sourced from untrusted sources. They can contain XSS that targets the end user.

import { useEffect, useState } from "react";
export const StringToHtml = () =>{
  const [html, setHtml] = useState<string>("")
  useEffect(() => {
    setHtml("<div >Html stored as a string</div>")
  }, [html])
  return(
      <div dangerouslySetInnerHTML={{__html: html}}></div>
  )
}
React Js dangerouslySetInnerHTML
Figure 2: React Js dangerouslySetInnerHTML

Using html-react-parser npm package

If you need more features such as conditional rendering, appending, replacing, etc., the html-react-parser NPM package can handle most of them.

Add the package:
npm install html-react-parser --save
or
yarn add html-react-parser

import { useEffect, useState } from "react";
import parse from 'html-react-parser';
export const StringToHtml = () =>{
  const [html, setHtml] = useState<string>("")
  useEffect(() => {
    setHtml("<div>Html stored as a string</div>")
  }, [html])
  return(
    <>
     {parse(html)}
    </>
  )
}
L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments