convert-svg-react
Version:
Converts SVG XML code to be used as ReactJS component.
63 lines (51 loc) • 2.31 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireDefault(require("react"));
var CreateSVG = function CreateSVG(nodeArray) {
return Array.prototype.map.call(nodeArray, function (node, i) {
var attributeObj = {};
var attributes = node.attributes,
localName = node.localName,
childNodes = node.childNodes,
nodeValue = node.nodeValue;
if (attributes) {
Array.from(attributes).forEach(function (attribute) {
console.log('attribute:', attribute);
if (attribute.name === "style") {
console.log(attribute.nodeValue);
var styleAttributes = attribute.nodeValue.split(";");
var styleObj = {}; // styleAttributes.reduce((obj, style) => {
// },{})
styleAttributes.forEach(function (attribute) {
var _attribute$split = attribute.split(":"),
_attribute$split2 = (0, _slicedToArray2["default"])(_attribute$split, 2),
key = _attribute$split2[0],
value = _attribute$split2[1];
styleObj[key] = value;
});
attributeObj[attribute.name] = styleObj; // When fromString gets ran classname is not concatinated
} else if (attribute.name === 'classname') {
attributeObj[attribute.name.replace(/n/, 'N')] = attribute.nodeValue;
} else if (attribute.name === 'fillrule') {
attributeObj[attribute.name.replace(/r/, 'R')] = attribute.nodeValue;
} else {
attributeObj[attribute.name] = attribute.nodeValue; // Adds inline style to svg
if (localName === 'svg') attributeObj.style = {
width: '5rem',
height: '5rem',
margin: '10px'
};
}
});
}
attributeObj.key = i;
return localName ? /*#__PURE__*/_react["default"].createElement(localName, attributeObj, childNodes && Array.isArray(Array.from(childNodes)) ? CreateSVG(Array.from(childNodes)) : []) : nodeValue;
});
};
var _default = CreateSVG;
exports["default"] = _default;