UNPKG

2.35 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 valueOnlyInputs = {
14 reset: true,
15 submit: true
16 };
17
18 var attributeName;
19 var attributeNameLowerCased;
20 var attributeValue;
21 var propName;
22 var propertyInfo;
23 var props = {};
24 var inputIsValueOnly = attributes.type && valueOnlyInputs[attributes.type];
25
26 for (attributeName in attributes) {
27 attributeValue = attributes[attributeName];
28
29 // ARIA (aria-*) or custom data (data-*) attribute
30 if (reactProperty.isCustomAttribute(attributeName)) {
31 props[attributeName] = attributeValue;
32 continue;
33 }
34
35 // convert HTML/SVG attribute to React prop
36 attributeNameLowerCased = attributeName.toLowerCase();
37 propName = getPropName(attributeNameLowerCased);
38
39 if (propName) {
40 propertyInfo = reactProperty.getPropertyInfo(propName);
41
42 // convert attribute to uncontrolled component prop (e.g., `value` to `defaultValue`)
43 // https://reactjs.org/docs/uncontrolled-components.html
44 if (
45 (propName === 'checked' || propName === 'value') &&
46 !inputIsValueOnly
47 ) {
48 propName = getPropName('default' + attributeNameLowerCased);
49 }
50
51 props[propName] = attributeValue;
52
53 switch (propertyInfo && propertyInfo.type) {
54 case reactProperty.BOOLEAN:
55 props[propName] = true;
56 break;
57 case reactProperty.OVERLOADED_BOOLEAN:
58 if (attributeValue === '') {
59 props[propName] = true;
60 }
61 break;
62 }
63 continue;
64 }
65
66 // preserve custom attribute if React >=16
67 if (utilities.PRESERVE_CUSTOM_ATTRIBUTES) {
68 props[attributeName] = attributeValue;
69 }
70 }
71
72 // transform inline style to object
73 utilities.setStyleProp(attributes.style, props);
74
75 return props;
76};
77
78/**
79 * Gets prop name from lowercased attribute name.
80 *
81 * @param {string} attributeName - Lowercased attribute name.
82 * @return {string}
83 */
84function getPropName(attributeName) {
85 return reactProperty.possibleStandardNames[attributeName];
86}