Skip to content

Commit b405b8b

Browse files
tyombspaulding
authored andcommitted
Hyphenate camelCased Preact props
As HTML attributes are not case sensitive and `setAttribute` converts camel case attributes to lower case we should use hyphens instead for compound words. However Preact/React convention is to use camel case for props. This converts hyphenated WC attributes to camel cased prop names.
1 parent 8ce7220 commit b405b8b

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

src/index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,12 @@ function toVdom(element, nodeName) {
4545
i = 0,
4646
a = element.attributes,
4747
cn = element.childNodes;
48-
for (i = a.length; i--; ) props[a[i].name] = a[i].value;
48+
for (i = a.length; i--; ) {
49+
var propName = a[i].name.replace(/-(\w)/, function(_, c) {
50+
return c ? c.toUpperCase() : ''
51+
});
52+
props[propName] = a[i].value;
53+
}
4954
for (i = cn.length; i--; ) children[i] = toVdom(cn[i]);
5055
return h(nodeName || element.nodeName.toLowerCase(), props, children);
5156
}

src/index.test.js

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,28 @@ import assert from 'assert';
22
import { h } from 'preact';
33
import registerElement from './index';
44

5-
function Clock ({ time }) {
6-
return <span>{time}</span>;
7-
}
8-
9-
registerElement(Clock, 'x-clock', ['time']);
5+
registerElement(Clock, 'x-clock', ['time', 'custom-date']);
106

117
it('renders ok, updates on attr change', () => {
128
const root = document.createElement('div');
139
const el = document.createElement('x-clock');
1410
el.setAttribute('time', '10:28:57 PM');
11+
el.setAttribute('custom-date', '11/11/2011');
1512

1613
root.appendChild(el);
1714
document.body.appendChild(root);
1815

1916
assert.equal(
2017
root.innerHTML,
21-
'<x-clock time="10:28:57 PM"><span>10:28:57 PM</span></x-clock>'
18+
'<x-clock time="10:28:57 PM" custom-date="11/11/2011"><span>10:28:57 PM, 11/11/2011</span></x-clock>'
2219
);
2320

2421
el.setAttribute('time', '11:01:10 AM');
22+
el.setAttribute('custom-date', '01/01/2001');
2523

2624
assert.equal(
2725
root.innerHTML,
28-
'<x-clock time="11:01:10 AM"><span>11:01:10 AM</span></x-clock>'
26+
'<x-clock time="11:01:10 AM" custom-date="01/01/2001"><span>11:01:10 AM, 01/01/2001</span></x-clock>'
2927
);
3028

3129
document.body.removeChild(root);

0 commit comments

Comments
 (0)