React component for rendering SVG icons from the Iconify ecosystem with over 200,000 icons from 150+ icon sets.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Utility functions for building and transforming SVG content from icon data. These functions provide low-level access to the icon rendering pipeline for advanced use cases.
Convert icon data and customizations into renderable SVG content with attributes.
/**
* Build SVG content from icon data and customizations
* @param icon - Icon data containing SVG body and metadata
* @param customisations - Optional customizations (size, rotation, flip, etc.)
* @returns Object containing SVG attributes and body content
*/
function buildIcon(
icon: IconifyIcon,
customisations?: IconifyIconCustomisations
): IconifyIconBuildResult;
interface IconifyIconBuildResult {
/** SVG element attributes (width, height, viewBox, etc.) */
attributes: Record<string, string>;
/** SVG body content (inner HTML) */
body: string;
}
interface IconifyIconCustomisations {
width?: IconifyIconSize;
height?: IconifyIconSize;
hFlip?: boolean;
vFlip?: boolean;
rotate?: string | number;
inline?: boolean;
}
type IconifyIconSize = number | string;Usage Examples:
import { buildIcon } from "@iconify/react";
const iconData = {
body: '<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>',
width: 24,
height: 24
};
// Build basic icon
const result = buildIcon(iconData);
console.log("Attributes:", result.attributes);
console.log("Body:", result.body);
// Build with customizations
const customResult = buildIcon(iconData, {
width: 32,
height: 32,
rotate: 1, // 90 degrees
hFlip: true,
color: "red"
});
// Use result to create SVG element
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
Object.entries(customResult.attributes).forEach(([key, value]) => {
svg.setAttribute(key, value);
});
svg.innerHTML = customResult.body;
// Build for different sizes
const sizes = [16, 24, 32, 48];
const builtIcons = sizes.map(size => buildIcon(iconData, {
width: size,
height: size
}));Replace ID attributes in SVG content to ensure uniqueness when multiple icons are used.
/**
* Replace IDs in SVG content to ensure uniqueness
* @param body - SVG body content containing potential ID attributes
* @param prefix - Prefix for new IDs, or function that returns unique ID
* @returns SVG content with replaced IDs
*/
function replaceIDs(
body: string,
prefix?: string | (() => string)
): string;Usage Examples:
import { replaceIDs } from "@iconify/react";
const svgBody = `
<defs>
<linearGradient id="grad1">
<stop offset="0%" stop-color="red"/>
<stop offset="100%" stop-color="blue"/>
</linearGradient>
</defs>
<rect width="100" height="100" fill="url(#grad1)"/>
`;
// Replace with string prefix
const uniqueBody1 = replaceIDs(svgBody, "icon1-");
console.log(uniqueBody1);
// Result: IDs become "icon1-grad1", etc.
// Replace with function for dynamic IDs
let counter = 0;
const uniqueBody2 = replaceIDs(svgBody, () => `dynamic-${++counter}-`);
console.log(uniqueBody2);
// Use in component creation
function createUniqueIcon(iconData: IconifyIcon, id: string) {
const built = buildIcon(iconData);
const uniqueBody = replaceIDs(built.body, `${id}-`);
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
Object.entries(built.attributes).forEach(([key, value]) => {
svg.setAttribute(key, value);
});
svg.innerHTML = uniqueBody;
return svg;
}
// Ensure uniqueness in React component
function CustomIconComponent({ iconData, componentId }) {
const built = buildIcon(iconData);
const safeBody = replaceIDs(built.body, `${componentId}-`);
return React.createElement("svg", {
...built.attributes,
dangerouslySetInnerHTML: { __html: safeBody }
});
}Calculate icon dimensions with proper aspect ratio handling and precision control.
/**
* Calculate icon dimensions with aspect ratio handling
* @param size - Input size (number, string, or 'auto')
* @param ratio - Aspect ratio (width/height)
* @param precision - Decimal precision for calculations (default: 2)
* @returns Calculated size value
*/
function calculateSize(
size: IconifyIconSize,
ratio: number,
precision?: number
): IconifyIconSize;
type IconifyIconSize = number | string;Usage Examples:
import { calculateSize } from "@iconify/react";
// Calculate height from width maintaining aspect ratio
const iconRatio = 24 / 16; // width/height = 1.5
const calculatedHeight = calculateSize(32, 1/iconRatio); // Calculate height from width
console.log("Height for width 32:", calculatedHeight); // Result: 21.33
// Calculate width from height
const calculatedWidth = calculateSize(20, iconRatio); // Calculate width from height
console.log("Width for height 20:", calculatedWidth); // Result: 30
// With custom precision
const preciseSize = calculateSize(32, 1/iconRatio, 4);
console.log("Precise calculation:", preciseSize); // More decimal places
// Handle string sizes
const stringSize = calculateSize("2em", iconRatio);
console.log("String size result:", stringSize); // Passes through string values
// Use in icon sizing logic
function getIconDimensions(originalIcon: IconifyIcon, targetWidth?: number, targetHeight?: number) {
const ratio = (originalIcon.width || 16) / (originalIcon.height || 16);
if (targetWidth && !targetHeight) {
return {
width: targetWidth,
height: calculateSize(targetWidth, 1/ratio)
};
} else if (targetHeight && !targetWidth) {
return {
width: calculateSize(targetHeight, ratio),
height: targetHeight
};
} else if (targetWidth && targetHeight) {
return { width: targetWidth, height: targetHeight };
} else {
return { width: originalIcon.width || 16, height: originalIcon.height || 16 };
}
}
// Example usage
const icon = { body: "...", width: 24, height: 16 };
const dimensions = getIconDimensions(icon, 48); // Width=48, Height=32 (maintains ratio)Combine building functions for complex icon manipulation.
import { buildIcon, replaceIDs, calculateSize } from "@iconify/react";
// Create responsive icon with multiple sizes
function createResponsiveIcon(iconData: IconifyIcon, sizes: number[]) {
const ratio = (iconData.width || 16) / (iconData.height || 16);
return sizes.map((size, index) => {
const height = calculateSize(size, 1/ratio);
const built = buildIcon(iconData, { width: size, height });
const uniqueBody = replaceIDs(built.body, `responsive-${index}-`);
return {
size,
attributes: built.attributes,
body: uniqueBody
};
});
}
// Create themed icon variants
function createThemedIcons(iconData: IconifyIcon, themes: Record<string, any>) {
return Object.entries(themes).map(([themeName, customizations]) => {
const built = buildIcon(iconData, customizations);
const themedBody = replaceIDs(built.body, `${themeName}-`);
return {
theme: themeName,
attributes: built.attributes,
body: themedBody
};
});
}
// Usage
const iconData = {
body: '<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>',
width: 24,
height: 24
};
const responsiveVersions = createResponsiveIcon(iconData, [16, 24, 32, 48]);
console.log("Responsive icons:", responsiveVersions);
const themedVersions = createThemedIcons(iconData, {
small: { width: 16, height: 16 },
medium: { width: 24, height: 24 },
large: { width: 32, height: 32, rotate: 1 },
flipped: { width: 24, height: 24, hFlip: true }
});
console.log("Themed icons:", themedVersions);Use building functions to create SVG elements programmatically.
import { buildIcon, replaceIDs } from "@iconify/react";
function createSVGElement(iconData: IconifyIcon, customizations?: any, idPrefix?: string): SVGSVGElement {
// Build the icon with customizations
const built = buildIcon(iconData, customizations);
// Ensure unique IDs if prefix provided
const body = idPrefix ? replaceIDs(built.body, idPrefix) : built.body;
// Create SVG element
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
// Set attributes
Object.entries(built.attributes).forEach(([key, value]) => {
svg.setAttribute(key, value);
});
// Set content
svg.innerHTML = body;
return svg;
}
// Create multiple unique SVG elements
const icons = [
{ name: "star", data: starIconData },
{ name: "heart", data: heartIconData },
{ name: "home", data: homeIconData }
];
const svgElements = icons.map((icon, index) =>
createSVGElement(icon.data, { width: 32, height: 32 }, `${icon.name}-${index}-`)
);
// Append to DOM
svgElements.forEach(svg => {
document.body.appendChild(svg);
});