Home > Software design >  HTML text in span - Tags not getting implemented
HTML text in span - Tags not getting implemented

Time:02-03

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>

CodePudding user response:

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</>

CodePudding user response:

<div dangerouslySetInnerHTML={{_html:textToRender}}/>

CodePudding user response:

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 onm ouseover="alert('mouseover');">ipsum</b>`
  const sanitizedData = () => ({
    __html: DOMPurify.sanitize(data)
  })

  return (
    <div
      dangerouslySetInnerHTML={sanitizedData()}
    />
  );
}

export default App;

CodePudding user response:

Please try it following way:

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

I hope it helps you.

  • Related