Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@
* @return {ReactElement|Array}
*/
function HTMLReactParser(html, options) {
if (typeof html !== 'string') {
throw new Error('`HTMLReactParser`: The first argument must be a string.');
}
return domToReact(htmlToDOM(html), options);
}

Expand Down
35 changes: 29 additions & 6 deletions lib/html-to-dom-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,22 +102,45 @@ function formatDOM(nodes, parentNode) {
* @return {Object} - The DOM nodes.
*/
function htmlToDOMClient(html) {
var root;
var match = typeof html === 'string' ? html.match(/<(.+?)>/) : null;
var tagName;
var parentNode;
var nodes;

if (match && typeof match[1] === 'string') {
tagName = match[1].toLowerCase();
}

// `DOMParser` can parse full HTML
// https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
if (window.DOMParser) {
if (tagName && window.DOMParser) {
var parser = new window.DOMParser();
root = parser.parseFromString(html, 'text/html');
var doc = parser.parseFromString(html, 'text/html');

// <head> and <body> are siblings
if (tagName === 'head' || tagName === 'body') {
nodes = doc.getElementsByTagName(tagName);

// document's child nodes
} else if (tagName === 'html') {
nodes = doc.childNodes;

// get the element's parent's child nodes
// do this in case of adjacent elements
} else {
parentNode = doc.getElementsByTagName(tagName)[0].parentNode;
nodes = parentNode.childNodes;
}

// otherwise, use `innerHTML`
// but this will strip out tags like <html> and <body>
} else {
root = document.createElement('div');
root.innerHTML = html;
parentNode = document.createElement('div');
parentNode.innerHTML = html;
nodes = parentNode.childNodes;
}

return formatDOM(root.childNodes);
return formatDOM(nodes);
}

/**
Expand Down
12 changes: 12 additions & 0 deletions test/html-to-react.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ describe('html-to-react', function() {
*/
describe('parser', function() {

it('throws an error if first argument is not a string', function() {
assert.throws(function() { Parser(); });

[undefined, null, {}, [], 42].forEach(function(arg) {
assert.throws(function() { Parser(arg); });
});
});

it('returns string if cannot be parsed to HTML', function() {
assert.equal(Parser('foo'), 'foo');
});

it('converts single HTML element to React', function() {
var html = data.html.single;
var reactElement = Parser(html);
Expand Down