skip to Main Content

I have span –

<span> {textToRender} </span>

I am rendering html text (as string) with span.

some text <br/> some text <br/> some text <ol>text

This is getting rendered as text only in javascript. Html tags are not getting applied over it.

<span> {textToRender} </span>

4

Answers


  1. This is expected, as React.js automatically escapes the extrapolations to prevent injection attacks and other vulnerabilities. In case you want HTML to get parsed, and proper tags be applied, you can use JSX instead of String or set HTML explicitly as follows:

    <span dangerouslySetInnerHTML={{ __html: textToRender }} />
    

    Or
    convert your textToRender to JSX.

    textToRender = <>some text <br/> some text <br/> some text</>
    
    Login or Signup to reply.
  2. <div dangerouslySetInnerHTML={{_html:textToRender}}/>
    
    Login or Signup to reply.
  3. same as the guys suggest you can use the dangerouslySetInnerHTML,
    Although the name suggests danger in dangerouslySetInnerHTML and its use, taking the necessary measure by using a well-developed sanitizer ensures the code to be clean and does not run unexpected scripts when rendered within the React node.
    you can use DOMPurify for exemple

    import DOMPurify from 'dompurify'
    
    const App = () => {
      const data = `lorem <b onmouseover="alert('mouseover');">ipsum</b>`
      const sanitizedData = () => ({
        __html: DOMPurify.sanitize(data)
      })
    
      return (
        <div
          dangerouslySetInnerHTML={sanitizedData()}
        />
      );
    }
    
    export default App;
    
    Login or Signup to reply.
  4. Please try it following way:

     <span dangerouslySetInnerHTML={{__html:textToRender}}></span>
    

    I hope it helps you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search