iconToSVG()

This function is part of Iconify Utils package.

Function iconToSVG() generates data required to render SVG.

It is used by all Iconify Icon components.

Usage

Function has the following parameters:

Function returns data with type IconifyIconBuildResult. See below.

Result

Result is an object with the following properties:

  • body, string. Icon content.
  • attributes, object. Attributes for <svg> element.
  • inline, boolean. Optional. If true, implementation should add the following style to generated icon: vertical-align: -0.125em;.

Result does not include attributes that are common to all <svg> elements, such as xmlns.

Examples of result

{
   "attributes": {
       "width": "24",
       "height": "24",
       "preserveAspectRatio": "xMidYMid meet",
       "viewBox": "0 0 24 24"
   },
   "body": "<path d=\"M7 6v12l10-6z\" fill=\"currentColor\"/>"
}
{
   "attributes": {
       "width": "24",
       "height": "24",
       "preserveAspectRatio": "xMidYMid meet",
       "viewBox": "0 0 24 24"
   },
   "body": "<path d=\"M5 13v-1h6V6h1v6h6v1h-6v6h-1v-6H5z\" fill=\"currentColor\"/>",
   "inline": true
}

Example

example.ts
import { icons } from '@iconify-json/codicon';
import { getIconData } from '@iconify/utils/lib/icon-set/get-icon';
import { iconToSVG } from '@iconify/utils/lib/svg/build';
import { defaults } from '@iconify/utils/lib/customisations';
import { replaceIDs } from '@iconify/utils/lib/svg/id';

const iconName = 'debug-console';

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

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

// Generate attributes for SVG element
const svgAttributes: Record<string, string> = {
   'xmlns': 'http://www.w3.org/2000/svg',
   'xmlns:xlink': 'http://www.w3.org/1999/xlink',
   ...renderData.attributes,
};
if (renderData.inline) {
   svgAttributes.style = 'vertical-align: -0.125em;';
}
const svgAttributesStr = Object.keys(svgAttributes)
   .map(
       (attr) =>
           // No need to check attributes for special characters, such as quotes,
           // they cannot contain anything that needs escaping.
           `${attr}="${svgAttributes[attr as keyof typeof svgAttributes]}"`
   )
   .join(' ');

// Generate SVG
const svg = `<svg ${svgAttributesStr}>${replaceIDs(renderData.body)}</svg>`;

// Log SVG
console.log(svg);