Reactjs convert html string to jsx

前端 未结 9 1320
夕颜
夕颜 2020-11-22 10:09

I\'m having trouble dealing with facebook\'s ReactJS. Whenever I do ajax and want to display an html data, ReactJS displays it as text. (See figure below)

相关标签:
9条回答
  • 2020-11-22 10:34

    For those still experimenting, npm install react-html-parser

    When I installed it it had 123628 weekly downloads.

    import ReactHtmlParser from 'react-html-parser'
    
    <div>{ReactHtmlParser(htmlString)}</div>
    
    0 讨论(0)
  • 2020-11-22 10:37

    There are now safer methods to accomplish this. The docs have been updated with these methods.

    Other Methods

    1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

      <div>{'First · Second'}</div>

    2. Safer - Use the Unicode number for the entity inside a Javascript string.

      <div>{'First \u00b7 Second'}</div>

      or

      <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

    3. Or a mixed array with strings and JSX elements.

      <div>{['First ', <span>&middot;</span>, ' Second']}</div>

    4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

      <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

    0 讨论(0)
  • 2020-11-22 10:42

    You can use the following if you want to render raw html in React

    <div dangerouslySetInnerHTML={{__html: `html-raw-goes-here`}} />
    

    Example - Render

    Test is a good day

    0 讨论(0)
提交回复
热议问题