Skip to content

Commit 115466b

Browse files
Handle conversion of <textarea> node to React properly
Setting textarea value in children is an antipattern in React. https://facebook.github.io/react/docs/forms.html#why-textarea-value The solution is to set value in `defaultValue` prop instead. Add test case for parsing textarea.
1 parent 2e27797 commit 115466b

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

lib/dom-to-react.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,12 @@ function domToReact(nodes) {
2727
children = null;
2828

2929
if (node.type === 'tag') {
30-
if (node.children) {
30+
// setting textarea value in children is an antipattern in React
31+
// https://facebook.github.io/react/docs/forms.html#why-textarea-value
32+
if (node.name === 'textarea' && node.children[0]) {
33+
node.attribs.defaultValue = node.children[0].data;
34+
35+
} else if (node.children) {
3136
// continue recursion of creating React elements
3237
children = domToReact(node.children);
3338
}

test/data.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"html": {
33
"single": "<p>foo</p>",
44
"multiple": "<p>foo</p><p>bar</p>",
5-
"complex": "<html><head><title>Title</title></head><body><header id=\"header\">Header</header><h1>Heading</h1><p>Paragraph</p><div class=\"class1 class2\">Some <em>text</em>.</div><script>alert();</script></body></html>"
5+
"complex": "<html><head><title>Title</title></head><body><header id=\"header\">Header</header><h1>Heading</h1><p>Paragraph</p><div class=\"class1 class2\">Some <em>text</em>.</div><script>alert();</script></body></html>",
6+
"textarea": "<textarea>foo</textarea>"
67
}
78
}

test/dom-to-react.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,17 @@ describe('dom-to-react parser', function() {
4040
);
4141
});
4242

43+
// https://facebook.github.io/react/docs/forms.html#why-textarea-value
44+
it('converts textarea correctly', function() {
45+
var html = data.html.textarea;
46+
var reactElement = domToReact(htmlToDOM(html));
47+
assert(React.isValidElement(reactElement));
48+
assert.deepEqual(
49+
reactElement,
50+
React.createElement('textarea', {
51+
defaultValue: 'foo'
52+
}, null)
53+
);
54+
});
55+
4356
});

0 commit comments

Comments
 (0)