UNPKG

1.64 kBJavaScriptView Raw
1var reactProperty = require('react-property');
2var utilities = require('./utilities');
3
4/**
5 * Converts HTML/SVG DOM attributes to React props.
6 *
7 * @param {object} [attributes={}] - HTML/SVG DOM attributes.
8 * @return {object} - React props.
9 */
10module.exports = function attributesToProps(attributes) {
11 attributes = attributes || {};
12
13 var attributeName;
14 var attributeNameLowerCased;
15 var attributeValue;
16 var propName;
17 var propertyInfo;
18 var props = {};
19
20 for (attributeName in attributes) {
21 attributeValue = attributes[attributeName];
22
23 // ARIA (aria-*) or custom data (data-*) attribute
24 if (reactProperty.isCustomAttribute(attributeName)) {
25 props[attributeName] = attributeValue;
26 continue;
27 }
28
29 // convert HTML/SVG attribute to React prop
30 attributeNameLowerCased = attributeName.toLowerCase();
31 propName = reactProperty.possibleStandardNames[attributeNameLowerCased];
32
33 if (propName) {
34 props[propName] = attributeValue;
35 propertyInfo = reactProperty.getPropertyInfo(propName);
36 switch (propertyInfo && propertyInfo.type) {
37 case reactProperty.BOOLEAN:
38 props[propName] = true;
39 break;
40 case reactProperty.OVERLOADED_BOOLEAN:
41 if (attributeValue === '') {
42 props[propName] = true;
43 }
44 break;
45 }
46 continue;
47 }
48
49 // preserve custom attribute if React >=16
50 if (utilities.PRESERVE_CUSTOM_ATTRIBUTES) {
51 props[attributeName] = attributeValue;
52 }
53 }
54
55 // transform inline style to object
56 utilities.setStyleProp(attributes.style, props);
57
58 return props;
59};