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

China☆狼群 提交于 2021-02-17 03:16:34

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/63389837/how-to-render-the-content-of-react-quill-without-the-html-markup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!