简体   繁体   中英

Dangerously Set innerHTML React

I have React frontend and strapi backend.

When inserting data into my strapi backend, the resulting output in my frontend contains html elements.

How can I show the output without the HTML elements? I have the following Gatsby code block,

import ReactMarkdown from "react-markdown"

<ReactMarkdown children={info_} />

The data within {info_} is outputted with the HTML elements, how can I use Dangerously Set innerHTML in my code or is there some other way to achieve this?

If you display an html node within the dangerouslySetInnerHTML property, you put your application at risk for XSS attacks. Long story short, the html could contain malicious code that would harm the user. If you do it, you need to sanitize the content before displaying it. The best option would be to use a battle-tested library such as sanitize-html-react .

You can use DOMParser to create a document from your HTML input and then extract the text like this:

new DOMParser().parseFromString(info_, 'text/html').body.textContent;

Here's an example using a functional form:

I tried putting this into a snippet demo, but the Stack Overflow snippet environment doesn't like something about the syntax. ☹️ You can copy and paste it in your JS console to try it.

Note that the embedded script never runs, but its source text is included in the output. If you want just part of the created document's text, you can use a method like Document.querySelector on the created document rather than its body .

function getTextFromHtml (html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent ?? '';
}

// Use:

// assuming `info_` is a string of valid HTML like this:
const info_ = `
<div>
  <p>Some text</p>
  <p>Some more text</p>
  <script>console.log('This script executed!')</script>
</div>
`;

const textContent = getTextFromHtml(info_);
console.log(textContent);

Afterward, you'll have plain text, so you won't need dangerouslySetInnerHTML .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM