Skip to content

Commit 2109b4c

Browse files
committed
Dont use self-closing tags, skip null and undefined JSX attributes, simpler prop generation using spread
1 parent 5e13ddc commit 2109b4c

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

src/index.js

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,8 @@ export default function renderToString(vnode) {
2121

2222
// components
2323
if (typeof nodeName==='function') {
24-
let props = { children },
24+
let props = { children, ...attributes },
2525
rendered;
26-
for (let i in attributes) if (HOP.call(attributes, i)) {
27-
props[i] = attributes[i];
28-
}
2926

3027
if (typeof nodeName.prototype.render!=='function') {
3128
// stateless functional components
@@ -42,14 +39,18 @@ export default function renderToString(vnode) {
4239

4340
// render JSX to HTML
4441
let s = `<${nodeName}`;
45-
for (let name in attributes) if (HOP.call(attributes, name)) {
46-
s += ` ${name}="${escape(attributes[name])}"`;
42+
for (let name in attributes) {
43+
if (HOP.call(attributes, name)) {
44+
let v = attributes[name];
45+
if (v!==null && v!==undefined) {
46+
s += ` ${name}="${escape(v)}"`;
47+
}
48+
}
4749
}
50+
s += '>';
4851
if (children && children.length) {
49-
s += `>${children.map(renderToString).join('')}</${nodeName}>`;
50-
}
51-
else {
52-
s += ' />';
52+
s += children.map(renderToString).join('');
5353
}
54+
s += `</${nodeName}>`
5455
return s;
5556
};

test/index.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ describe('render-to-string', () => {
1313

1414
expect(rendered).to.equal(expected);
1515
});
16+
17+
it('should omit null and undefined attributes', () => {
18+
let rendered = render(<div a={null} b={undefined} />),
19+
expected = `<div></div>`;
20+
21+
expect(rendered).to.equal(expected);
22+
});
1623
});
1724

1825
describe('Functional Components', () => {

0 commit comments

Comments
 (0)