Skip to content

iconToSVG() ​

This function is part of Iconify Utils package.

Function iconToSVG() generates data required to render SVG.

Usage ​

This function has the following parameters:

This function returns data with type IconifyIconBuildResult. See below.

Parsing SVG ​

This function uses IconifyIcon as a source. If you want to parse a string that contains SVG, use parseSVGContent() and buildParsedSVG() functions instead.

Result ​

The result is an object with the following properties:

  • body, string. Icon content.
  • attributes, object. Attributes for <svg> element.
  • viewBox, SVGViewBox. viewBox as array of numbers.

List of attributes in the result does not include xmlns because it is identical in all SVG. It always includes viewBox, usually includes width and height.

You can use iconToHTML() to convert the result to string.

Examples of result ​

json{
   "attributes": {
       "width": "24",
       "height": "24",
       "viewBox": "0 0 24 24"
   },
   "viewBox": [0, 0, 24, 24],
   "body": "<path d=\"M7 6v12l10-6z\" fill=\"currentColor\"/>"
}

Example ​

example.ts
tsimport { icons } from '@iconify-json/codicon';
import { getIconData, iconToSVG, iconToHTML, replaceIDs } from '@iconify/utils';

const iconName = 'debug-console';

// Get content for icon
const iconData = getIconData(icons, iconName);
if (!iconData) {
   throw new Error(`Icon "${iconName}" is missing`);
}

// Use it to render icon
const renderData = iconToSVG(iconData, {
   height: 'auto',
});

// Generate SVG string
const svg = iconToHTML(replaceIDs(renderData.body), renderData.attributes);

// Log SVG
console.log(svg);

Icon dimensions ​

By default, resulting attributes include width and height, where height is set to "1em".

If you want to remove dimensions, set height to "unset" or "none" in customisations parameter:

jsconst result = iconToSVG(data, {
   // Setting only height will also remove width
   height: 'unset',
});