UNPKG

1.89 kBJavaScriptView Raw
1var reactProperty = require('react-property');
2var utilities = require('./utilities');
3
4var setStyleProp = utilities.setStyleProp;
5
6var htmlProperties = reactProperty.html;
7var svgProperties = reactProperty.svg;
8var isCustomAttribute = reactProperty.isCustomAttribute;
9
10var hasOwnProperty = Object.prototype.hasOwnProperty;
11
12/**
13 * Converts HTML/SVG DOM attributes to React props.
14 *
15 * @param {object} [attributes={}] - HTML/SVG DOM attributes.
16 * @return {object} - React props.
17 */
18function attributesToProps(attributes) {
19 attributes = attributes || {};
20
21 var attributeName;
22 var attributeNameLowerCased;
23 var attributeValue;
24 var property;
25 var props = {};
26
27 for (attributeName in attributes) {
28 attributeValue = attributes[attributeName];
29
30 // ARIA (aria-*) or custom data (data-*) attribute
31 if (isCustomAttribute(attributeName)) {
32 props[attributeName] = attributeValue;
33 continue;
34 }
35
36 // convert HTML attribute to React prop
37 attributeNameLowerCased = attributeName.toLowerCase();
38 if (hasOwnProperty.call(htmlProperties, attributeNameLowerCased)) {
39 property = htmlProperties[attributeNameLowerCased];
40 props[property.propertyName] =
41 property.hasBooleanValue ||
42 (property.hasOverloadedBooleanValue && !attributeValue)
43 ? true
44 : attributeValue;
45 continue;
46 }
47
48 // convert SVG attribute to React prop
49 if (hasOwnProperty.call(svgProperties, attributeName)) {
50 property = svgProperties[attributeName];
51 props[property.propertyName] = attributeValue;
52 continue;
53 }
54
55 // preserve custom attribute if React >=16
56 if (utilities.PRESERVE_CUSTOM_ATTRIBUTES) {
57 props[attributeName] = attributeValue;
58 }
59 }
60
61 // transform inline style to object
62 setStyleProp(attributes.style, props);
63
64 return props;
65}
66
67module.exports = attributesToProps;