Skip to content

Commit 24cce18

Browse files
Create helper that makes DOM attributes compatible with React props
Currently, the helper only makes the CSS style attribute compatible by converting the string to an object.
1 parent 6834026 commit 24cce18

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

lib/attributes-to-props.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
'use strict';
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
var utilities = require('./utilities');
7+
8+
/**
9+
* Make attributes compatible with React props.
10+
*
11+
* @param {Object} attr - The attributes.
12+
* @return {Object} - The props.
13+
*/
14+
function attributesToProps(attr) {
15+
attr = attr || {};
16+
17+
if (attr.style) {
18+
attr.style = cssToJs(attr.style);
19+
}
20+
21+
return attr;
22+
}
23+
24+
/**
25+
* Convert CSS style string to JS style object.
26+
*
27+
* @param {String} style - The CSS style.
28+
* @return {Object} - The JS style object.
29+
*/
30+
function cssToJs(style) {
31+
if (typeof style !== 'string') {
32+
throw new Error('`cssToJs`: first argument must be a string. ');
33+
}
34+
35+
var result = {};
36+
// e.g., `color: #f00`
37+
var declarations = style.split(';');
38+
// css property itemized as key and value
39+
var properties;
40+
var j;
41+
var propertiesLen;
42+
43+
for (var i = 0, declarationsLen = declarations.length; i < declarationsLen; i++) {
44+
properties = declarations[i].trim().split(':');
45+
46+
// skip if not a css property
47+
if (properties.length !== 2) { continue; }
48+
49+
// css property name
50+
properties[0] = properties[0].trim();
51+
// css property value
52+
properties[1] = properties[1].trim();
53+
54+
if (properties[0] && properties[1]) {
55+
for (j = 0, propertiesLen = properties.length; j < propertiesLen; j++) {
56+
result[utilities.camelCase(properties[0])] = properties[1];
57+
}
58+
}
59+
}
60+
61+
return result;
62+
}
63+
64+
/**
65+
* Export attributes to props helper.
66+
*/
67+
module.exports = attributesToProps;

0 commit comments

Comments
 (0)