html-react-parser
Version:
HTML to React parser.
92 lines (75 loc) • 2.43 kB
JavaScript
var reactProperty = require('react-property');
var styleToObject = require('style-to-object');
var utilities = require('./utilities');
var camelCase = utilities.camelCase;
var htmlProperties = reactProperty.html;
var svgProperties = reactProperty.svg;
var isCustomAttribute = reactProperty.isCustomAttribute;
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Converts HTML/SVG DOM attributes to React props.
*
* @param {Object} [attributes={}] - The HTML/SVG DOM attributes.
* @return {Object} - The React props.
*/
function attributesToProps(attributes) {
attributes = attributes || {};
var attributeName;
var attributeNameLowerCased;
var attributeValue;
var property;
var props = {};
for (attributeName in attributes) {
attributeValue = attributes[attributeName];
// ARIA (aria-*) or custom data (data-*) attribute
if (isCustomAttribute(attributeName)) {
props[attributeName] = attributeValue;
continue;
}
// convert HTML attribute to React prop
attributeNameLowerCased = attributeName.toLowerCase();
if (hasOwnProperty.call(htmlProperties, attributeNameLowerCased)) {
property = htmlProperties[attributeNameLowerCased];
props[property.propertyName] =
property.hasBooleanValue ||
(property.hasOverloadedBooleanValue && !attributeValue)
? true
: attributeValue;
continue;
}
// convert SVG attribute to React prop
if (hasOwnProperty.call(svgProperties, attributeName)) {
property = svgProperties[attributeName];
props[property.propertyName] = attributeValue;
continue;
}
// preserve custom attribute if React >=16
if (utilities.PRESERVE_CUSTOM_ATTRIBUTES) {
props[attributeName] = attributeValue;
}
}
// convert inline style to object
if (attributes.style != null) {
props.style = cssToJs(attributes.style);
}
return props;
}
/**
* Converts inline CSS style to POJO (Plain Old JavaScript Object).
*
* @param {String} style - The inline CSS style.
* @return {Object} - The style object.
*/
function cssToJs(style) {
var styleObject = {};
if (style) {
styleToObject(style, function (property, value) {
// skip CSS comment
if (property && value) {
styleObject[camelCase(property)] = value;
}
});
}
return styleObject;
}
module.exports = attributesToProps;