Skip to content
Advertisement

How to render the content of React Quill without the html markup?

I managed to get my Quill working, but now I wanted to display the contents from the editor without the html markup. I tried using react-render-html npm package, it was working fine before but now it is no longer maintained and gives me a error

Could not find a declaration file for module 'react-render-html'. /path/to/module
implicitly has an 'any' type.
  Try `npm install @types/react-render-html` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-render-html';

also it shows up with html markup. So i tried using react-html-parser , htmr , html-to-react npm packages , it works perfectly for single elements but it is not working for multiple elements. So i tried console.log to see what i am receiving from backend which gave me this

<p>&lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt; &lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt; &lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt; &lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt; &lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt;

Now i wanted to render this without the html markup , so i did again console.log to see whether it is getting converted properly by doing

  //import renderHtml from 'htmr';
  //import renderHtml from 'html-to-react';

    import renderHtml from 'react-html-parser';
 
  console.log(renderHtml(${blog.excerpt}))

and ultimately it gave me this

<h2>Hello</h2><p>how are you ? </p>
<h2>Hello</h2><p>how are you ? </p> 
<h2>Hello</h2><p>how are you ? </p> 
<h2>Hello</h2><p>how are you ? </p> 
<h2>Hello</h2><p>how are you ? </p>

I also tried with dangerouslysetinnerhtml but it isn’t working again

Advertisement

Answer

Looking at your server response, the HTML tag is escaped. You need to escape it first before passing to HTML parser.

You can use html-entities to decode the server response. The easiest way is to replace all &lt; and &gt; characters.

const decodedHtml = htmlEntities.decode(html)
// or
const decodedHtml = html.replace(/&lt;/g, '<').replace(/&gt;/g, '>')

return htmr(decodedHtml)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement