Sanitize HTML String without using dangerouslySetInnerHTML to check length

Can I sanitize a string without using the dangerous SetInnerHTML in React JSX. The requirement is to check the length of the html sanitized string and then enable only the component. Sort of

var SomeComponent = React.createClass({ render:function(){ return ( {this.props.htmlString.length > 0 ? <Child htmlString={this.props.htmlString} : null} ) } }) var Child = React.createClass({ render:function(){ return ( <p dangerouslySetInnerHTML={{__html: this.props.htmlString}}></p> ) } }) 

Everything works fine, but doesn't work when this.props.htmlString=' ' . In this case, length> 0 and the component are included. Therefore, I want to check the length of innerHTML before the element itself is included.

One possible solution I came across something like:

 var html = "&nbsp;"; var div = document.createElement('div'); div.innerHTML = html; //check the length of innerHTML now 

But I'm looking for a cleaner one more type of reaction.

+5
source share
1 answer

As you said, resolving an HTML string into plain text is easily done by populating the DOM element.

 function htmlToText(htmlString) { const el = document.createElement('div'); el.innerHTML = htmlString; return el.textContent; } 

This turns your markup into plain text:

 htmlToText('&nbsp;') === '\xa0' // non-breaking space character 

Checking that the allowed text is not empty is then trivial:

 htmlToText('&nbsp;').trim().length === 0 htmlToText('&nbsp; FOO ').trim().length === 3 

There is no โ€œResponsiveโ€ way, because if you customize the HTML directly from a string, it is only allowed when actually entering the DOM. Of course, you can use this tool to create an HOC :

 const nonEmptyHtml = Component => props => { const html = props.dangerouslySetInnerHTML; if (html && !htmlToText(html).trim().length) { return null; } return <Component {...props} />; }; 

Using:

 const NonEmptyParagraph = nonEmptyHtml('p'); ReactDOM.render(<NonEmptyParagraph dangerouslySetInnerHTML={htmlString} />); 
+2
source

Source: https://habr.com/ru/post/1240152/


All Articles