Skip to content

Commit 5abad70

Browse files
committed
Skip falsey attributes and children - fixes Issue #2
1 parent 88911c1 commit 5abad70

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/index.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ let encodeEntities = s => String(s).replace(/[<>"&]/g, escapeChar);
1616

1717
let escapeChar = a => ESC[a] || a;
1818

19+
let falsey = v => v==null || v===false;
20+
1921

2022
/** Render Preact JSX + Components to an HTML string.
2123
* @name render
@@ -100,7 +102,7 @@ export default function renderToString(vnode, context, opts, inner) {
100102
if (name==='dangerouslySetInnerHTML') {
101103
html = v && v.__html;
102104
}
103-
else if (v!==null && v!==undefined && typeof v!=='function') {
105+
else if (!falsey(v) && typeof v!=='function') {
104106
s += ` ${name}="${encodeEntities(v)}"`;
105107
}
106108
}
@@ -114,7 +116,10 @@ export default function renderToString(vnode, context, opts, inner) {
114116
let len = children && children.length;
115117
if (len) {
116118
for (let i=0; i<len; i++) {
117-
s += renderToString(children[i], context, opts, true);
119+
let child = children[i];
120+
if (!falsey(child)) {
121+
s += renderToString(child, context, opts, true);
122+
}
118123
}
119124
}
120125
else if (opts && opts.xml) {

test/render.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ describe('render', () => {
1414
expect(rendered).to.equal(expected);
1515
});
1616

17-
it('should omit null and undefined attributes', () => {
18-
let rendered = render(<div a={null} b={undefined} />),
17+
it('should omit falsey attributes', () => {
18+
let rendered = render(<div a={null} b={undefined} c={false} />),
1919
expected = `<div></div>`;
2020

2121
expect(rendered).to.equal(expected);
@@ -34,6 +34,13 @@ describe('render', () => {
3434

3535
expect(rendered).to.equal(expected);
3636
});
37+
38+
it('should omit falsey children', () => {
39+
let rendered = render(<div>{null}|{undefined}|{false}</div>),
40+
expected = `<div>||</div>`;
41+
42+
expect(rendered).to.equal(expected);
43+
});
3744
});
3845

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

0 commit comments

Comments
 (0)