forked from remarkablemark/html-react-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathattributes-to-props.js
88 lines (74 loc) · 2.36 KB
/
attributes-to-props.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var reactProperty = require('react-property');
var utilities = require('./utilities');
/**
* Converts HTML/SVG DOM attributes to React props.
*
* @param {object} [attributes={}] - HTML/SVG DOM attributes.
* @param {string} [nodeName] - DOM node name.
* @returns - React props.
*/
module.exports = function attributesToProps(attributes, nodeName) {
attributes = attributes || {};
var valueOnlyInputs = {
reset: true,
submit: true
};
var attributeName;
var attributeNameLowerCased;
var attributeValue;
var propName;
var propertyInfo;
var props = {};
var inputIsValueOnly = attributes.type && valueOnlyInputs[attributes.type];
for (attributeName in attributes) {
attributeValue = attributes[attributeName];
// ARIA (aria-*) or custom data (data-*) attribute
if (reactProperty.isCustomAttribute(attributeName)) {
props[attributeName] = attributeValue;
continue;
}
// convert HTML/SVG attribute to React prop
attributeNameLowerCased = attributeName.toLowerCase();
propName = getPropName(attributeNameLowerCased);
if (propName) {
propertyInfo = reactProperty.getPropertyInfo(propName);
// convert attribute to uncontrolled component prop (e.g., `value` to `defaultValue`)
// https://reactjs.org/docs/uncontrolled-components.html
if (
(propName === 'checked' || propName === 'value') &&
nodeName !== 'option' &&
!inputIsValueOnly
) {
propName = getPropName('default' + attributeNameLowerCased);
}
props[propName] = attributeValue;
switch (propertyInfo && propertyInfo.type) {
case reactProperty.BOOLEAN:
props[propName] = true;
break;
case reactProperty.OVERLOADED_BOOLEAN:
if (attributeValue === '') {
props[propName] = true;
}
break;
}
continue;
}
// preserve custom attribute if React >=16
if (utilities.PRESERVE_CUSTOM_ATTRIBUTES) {
props[attributeName] = attributeValue;
}
}
// transform inline style to object
utilities.setStyleProp(attributes.style, props);
return props;
};
/**
* Gets prop name from lowercased attribute name.
*
* @param {string} attributeName - Lowercased attribute name.
* @returns - Prop name.
*/
function getPropName(attributeName) {
return reactProperty.possibleStandardNames[attributeName];
}