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(' ') === '\xa0'
Checking that the allowed text is not empty is then trivial:
htmlToText(' ').trim().length === 0 htmlToText(' 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} />);
hon2a source share