Dangerous html react это

When to use dangerouslySetInnerHTML in React?

Rendering HTML markup from rich text created in a WYSIWYG editor might be difficult. Because numerous pieces of logic are required to make things work as they should. This can be attributed to the fact that React uses a browser-independent system to manipulate the DOM elements, thus preventing direct interaction with the DOM. Things can be pretty much easier and faster with dangerouslySetInnerHTML.

In this tutorial, we’ll see how to use dangerouslySetInnerHTML in a React application.

What is dangerouslySetInnerHTML?​

React dangerouslySetInnerHTML is an HTML property that makes it easy to programmatically set the HTML elements from an external source. It has replaced the innerHTML used in the browser DOM. dangerouslySetInnerHTML helps React know how to handle the HTML elements in a component where the contents are to be rendered.

When to use dangerouslySetInnerHTML?​

dangerouslySetInnerHTML is mostly used in any application where you need to render formatted text in a div element. Also, you can use it to render content exactly as you have formatted it. For instance, let’s consider a blog application. The body of a blog is usually formatted with headers, paragrams, images, code blocks, etc.

To render such contents in a React application, you’ll need to manipulate the DOM to get the HTML elements in the contents and set them to an element using innerHTML. Because React does not allow direct interaction with the DOM, your content will end up not being displayed as it should. However, when dangerouslySetInnerHTML is applied, React recognizes the HTML tags and correctly renders them.

Due to its vulnerability to cross-site scripting (XSS) attacks, dangerouslySetInnerHTML might constitute a major threat to your application, as the name suggests. However, DOMPurify has proven to be a highly effective tool in overcoming such difficulties. DOMPurify is a DOM-only XSS sanitizer for HTML for preventing XSS attacks by stripping out all dangerous HTML in content rendered in an application.

For example, if users are permitted to insert HTML directly into a web page via a form field, hackers can embed malicious code into the application, causing the application to behave inappropriately or even resulting in data loss. Consider the following code:

const App = () =>   const data = `lorem ipsum`;  return ( div dangerouslySetInnerHTML=__html: data>> /> ); > 

A piece of JavaScript code was embedded in the above code. This will trigger an alert each time a user tries to access the application. This is because the data was not sanitized before being rendered in the application. The above code will return the below result.

lorem ipsum img src="" onerror="alert('mailicious message');" /> 

As shown below, you can sanitize the data to remove all malicious code and scripts embedded in it.

import DOMPurify from 'dompurify';  const App = () =>   const data = `lorem test`  const sanitizedData = () => (  __html: DOMPurify.sanitize(data) >)  return (  dangerouslySetInnerHTML=__html: DOMPurify.sanitize(data)>>>div> ); >  export default App; 

The above code will strip out the script in the data that has been rendered on the application and the result below.

Building a simple example app​

To demonstrate how dangerouslySetInnerHTML works in a React application, let’s build a simple blog application. To make things easier, we’ll use superplate CLI to create React apps.

To get started, create a new app with the command below.

The above command will prompt you to choose the configuration for your project. Your selection should look like the screenshot below.

dangerouslySetInnerhtml cli

Once you complete the prompts, Superlate will install all the required packages and set up the project folders for your application.

Now install the Dompurify module to sanitize the HTML codes we’ll render in the app.

npm install dompurify @types/dompurify 

Next, open the application in your favorite text editor. Then create a data.json file in the src folder of the project and add the dummy data below.

  "blogs": [   "title": "

Node.js for begineers

"
, "content": "

Lorem ipsum dolor sit amet consectetur adipisicing elit. Enim ex a veniam, molestiae praesentium culpa, mollitia officiis quas quia vitae voluptates

"
>, "title": "

Sit amet consectetur adipisicing eli

"
, "content": "

Lorem ipsum dolor sit amet consectetur adipisicing elit. Enim ex a veniam, molestiae praesentium culpa, mollitia officiis quas quia vitae voluptates

"
>, "title": "

Sit amet consectetur adipisicing eli

"
, "content": "

Lorem ipsum dolor sit amet consectetur adipisicing elit. Enim ex a veniam, molestiae praesentium culpa, mollitia officiis quas quia vitae voluptates

"
> ] >

In the above JSON data, we created some HTML formatted blog data we’ll render to the application.

Now update the code in the pages/index.ts file to render the data with the code snippet below.

import React from "react"; import DOMPurify from "dompurify"; import  Row, Col, Container, Card > from "react-bootstrap"; import data from "../data.json"  const Home: React.FC = () =>   return ( div className="d-flex flex-column min-vh-100"> Container className="my-5 flex-grow-1"> Row> (data.blogs.map((data) => ( Col md=4> key=data.title> className="mb-3"> Card className="border-none"> Card.Body> Card.Title> div dangerouslySetInnerHTML=__html: DOMPurify.sanitize(data.title)>>>div> Card.Title> Card.Text> div dangerouslySetInnerHTML=__html: DOMPurify.sanitize(data.content)>>>div> Card.Text> Card.Body> Card> Col> )))> Row> Container> div> ); >;  export default Home; 

In the above code snippet, we imported dompurify to sanitize the contents in the blog, react-bootstrap components to style the application, and the dummy JSON data we created. Then in the card, we looped through the blogs to access and render the data in the objects.

For the Card title and Text, we added div elements and attached the dangerouslySetInnerHTML property to render the contents according to how they were formatted.

To allow the div where the contents are rendered to have children, we passed in the —html key to dangerouslySetInnerHTML and wrapped the content to be rendered in the dompurify sanitize method.

dangerouslySetInnerhtml usage

In the above screenshot, dangerouslySetInnerHTML has rendered the contents just the way they were been formatted to look like.

discord banner

Conclusion​

dangerouslySetInnerHTML in a React application. We started by explaining what dangerouslySetInnerHTML is, when to use it, and the best practices for using it in a React application.

What is Strict Mode in React 18 and how to use it to find and fix bugs in your React application.

We’ll build a React admin tutorial app with refine

We’ll implement Conditional Rendering in React and the various ways to use it in your React applications.

Источник

Using dangerouslySetInnerHTML in a React application

Using DangerouslySetInnerHTML In A React Application

This article covers the reasoning behind using the dangerouslySetInnerHTML property in a React application, which is the equivalent of the innerHTML attribute in browser DOM.

What is dangerouslySetInnerHTML ?

dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML , you can use this property directly on the element.

When dangerouslySetInnerHTML is used, React also knows that the content of that specific element is dynamic, and, for the children of that node, it simply skips the comparison against the virtual DOM to gain some extra performance.

As the name of the property suggests, it can be dangerous to use because it makes your code vulnerable to cross-site scripting (XSS) attacks. This becomes an issue especially if you are fetching data from a third-party source or rendering content submitted by users.

When to use dangerouslySetInnerHTML

A use case where you need to set the HTML content of a DOM element is when you populate a element with the data coming from a rich text editor. Imagine you have a webpage where people can submit comments and you allow them to use a rich text editor. In this case, the output of that rich text editor is likely to be HTML with tags such as

, , and .

Consider the following code snippet, which would render the string without being aware of the tag in it — meaning that the output would be just the string itself without any bold text, like so: lorem ipsum.

const App = () => < const data = 'lorem ipsum'; return ( ); > export default App;

But when dangerouslySetInnerHTML is used, React becomes aware of the HTML tags and renders them properly. This time, the output would be rendered correctly with bold text (i.e., lorem ipsum).

const App = () => < const data = 'lorem ipsum'; return ( > /> ); > export default App;

Note that it should be an object with the __html key passed to dangerouslySetInnerHTML . Other than that, the element you use the dangerouslySetInnerHTML property on should not have any children, hence the use of element as a self-closing tag.

The requirement for passing an object is just another safeguard to prevent developers from using it without going through the documentation and becoming aware of the potential danger.

Sanitization when using dangerouslySetInnerHTML

The examples above pose no danger when rendered. However, there might be some cases where an HTML element executes a script.

Consider the following examples where a JavaScript event is attached to an HTML element. Although these are harmless examples, they are proof of concepts that show how an HTML element can be exploited to run malicious scripts.

Over 200k developers use LogRocket to create better digital experiences

Learn more →

const App = () => < const data = `lorem ipsum`; return ( > /> ); > export default App; const App = () => < const data = `lorem ipsum `; return ( > /> ); > export default App;

Luckily, there are sanitization tools for HTML, which detect potentially malicious parts in HTML code and then output a clean and safe version of it. The most popular sanitizer for HTML is DOMPurify.

Let’s use its online demo to sanitize the above-mentioned HTML codes and see how it detects and filters out parts of the code that are likely to be dangerous when executed.

Original lorem ipsum Sanitized lorem ipsum 

Original lorem ipsum Sanitized lorem ipsum

It’s good practice to use a sanitizer even when we trust the source of the data. With the DOMPurify package used, one of the examples above would be as follows:

import DOMPurify from 'dompurify' const App = () => < const data = `lorem ipsum` const sanitizedData = () => (< __html: DOMPurify.sanitize(data) >) return ( /> ); > export default App;

The sanitizedData function returns an object with the __html key, which has a value returned from the DOMPurify.sanitize function.

As expected, when we hover over the bold text, there is no alert function executed.

Note that because DOMPurify needs a DOM tree and the Node environment does not have one, you either have to use the jsdom package to create a window object and initialize DOMPurify with it, or use the isomorphic-dompurify package alone instead, which encapsulates both the DOMPurify and jsdom packages.

If you prefer the first option, you can refer to the following snippet from the documentation of DOMPurify .

const createDOMPurify = require('dompurify'); const < JSDOM >= require('jsdom'); const window = new JSDOM('').window; const DOMPurify = createDOMPurify(window); const clean = DOMPurify.sanitize(dirty);

Conclusion

In conclusion, dangerouslySetInnerHTML is nothing but a replacement of innerHTML in React and should be used with care. Although the name suggests danger in its use, taking the necessary measure by using a well-developed sanitizer ensures the code is clean and does not run unexpected scripts when rendered within the React node.

Get set up with LogRocket’s modern React error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.
$ npm i --save logrocket 

// Code:

import LogRocket from 'logrocket';
LogRocket.init('app/id');
Add to your HTML:

script src="https://cdn.lr-ingest.com/LogRocket.min.js"> /script>
script>window.LogRocket && window.LogRocket.init('app/id');script>

Источник

Читайте также:  Javascript что такое split
Оцените статью