Skip to content

Commit 7fabd3f

Browse files
committed
Fix JSX rendering being non-deterministic about empty VNodes
1 parent 6996c91 commit 7fabd3f

File tree

2 files changed

+39
-16
lines changed

2 files changed

+39
-16
lines changed

src/index.js

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ export default function renderToString(vnode, context, opts, inner) {
5757
let pretty = opts.pretty,
5858
indentChar = typeof pretty==='string' ? pretty : '\t';
5959

60+
if (vnode==null) {
61+
return '<!---->';
62+
}
63+
6064
// #text nodes
6165
if (!nodeName) {
6266
return encodeEntities(vnode);
@@ -153,31 +157,31 @@ export default function renderToString(vnode, context, opts, inner) {
153157
s += html;
154158
}
155159
else {
156-
let len = children && children.length;
157-
if (len) {
158-
let pieces = [],
159-
hasLarge = ~s.indexOf('\n');
160-
for (let i=0; i<len; i++) {
161-
let child = children[i];
162-
if (!falsey(child)) {
163-
let ret = renderToString(child, context, opts, true);
164-
if (!hasLarge && pretty && isLargeString(ret)) hasLarge = true;
165-
pieces.push(ret);
166-
}
160+
let len = children && children.length,
161+
pieces = [],
162+
hasLarge = ~s.indexOf('\n');
163+
for (let i=0; i<len; i++) {
164+
let child = children[i];
165+
if (!falsey(child)) {
166+
let ret = renderToString(child, context, opts, true);
167+
if (!hasLarge && pretty && isLargeString(ret)) hasLarge = true;
168+
pieces.push(ret);
167169
}
168-
if (hasLarge) {
169-
for (let i=pieces.length; i--; ) {
170-
pieces[i] = '\n' + indentChar + indent(pieces[i], indentChar);
171-
}
170+
}
171+
if (hasLarge) {
172+
for (let i=pieces.length; i--; ) {
173+
pieces[i] = '\n' + indentChar + indent(pieces[i], indentChar);
172174
}
175+
}
176+
if (pieces.length) {
173177
s += pieces.join('');
174178
}
175179
else if (opts && opts.xml) {
176180
return s.substring(0, s.length-1) + ' />';
177181
}
178182
}
179183

180-
if (VOID_ELEMENTS.indexOf(nodeName) === -1) {
184+
if (opts.jsx || VOID_ELEMENTS.indexOf(nodeName)===-1) {
181185
if (pretty && ~s.indexOf('\n')) s += '\n';
182186
s += `</${nodeName}>`;
183187
}

test/jsx.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,4 +105,23 @@ describe('jsx', () => {
105105
</a>
106106
`);
107107
});
108+
109+
it('should render empty resolved children identically to no children', () => {
110+
const Empty = () => null;
111+
expect(renderJsx(
112+
<div>
113+
<a />
114+
<b>{null}</b>
115+
<c><Empty /></c>
116+
</div>
117+
)).to.equal(dedent`
118+
<div>
119+
<a />
120+
<b />
121+
<c>
122+
<!---->
123+
</c>
124+
</div>
125+
`);
126+
});
108127
});

0 commit comments

Comments
 (0)