UNPKG

lucide-react

Version:

A Lucide icon library package for React applications.

1 lines 2.72 kB
{"version":3,"file":"DynamicIcon.mjs","sources":["../../src/DynamicIcon.ts"],"sourcesContent":["'use client';\n\nimport { createElement, forwardRef, useEffect, useState } from 'react';\nimport { LucideIcon, LucideIconData, LucideProps } from './types';\nimport dynamicIconImports from './dynamicIconImports';\nimport Icon from './Icon';\n\nexport type DynamicIconModule = {\n default: LucideIcon;\n __iconData?: LucideIconData;\n};\n\nexport type IconName = keyof typeof dynamicIconImports;\n\nexport const iconNames = Object.keys(dynamicIconImports) as Array<IconName>;\n\ninterface DynamicIconComponentProps extends LucideProps {\n name: IconName;\n fallback?: () => JSX.Element | null;\n}\n\nasync function getIconData(name: IconName) {\n if (!(name in dynamicIconImports)) {\n throw new Error('[lucide-react]: Name in Lucide DynamicIcon not found');\n }\n\n // TODO: Replace this with a generic iconNode package.\n const icon = (await dynamicIconImports[name]()) as DynamicIconModule;\n\n if (icon.__iconData != null) {\n return icon.__iconData;\n }\n\n throw new Error('[lucide-react]: Failed to resolve icon data for DynamicIcon');\n}\n\n/**\n * Dynamic Lucide icon component\n *\n * @component Icon\n * @param {object} props\n * @param {string} props.color - The color of the icon\n * @param {number} props.size - The size of the icon\n * @param {number} props.strokeWidth - The stroke width of the icon\n * @param {boolean} props.absoluteStrokeWidth - Whether to use absolute stroke width\n * @param {boolean} props.nonScalingStroke - Whether to use non scaling strokes\n * @param {string} props.className - The class name of the icon\n * @param {LucideIconNode[]} props.children - The children of the icon\n * @param {LucideIconNode[]} props.iconNode - The icon node of the icon\n *\n * @returns {ForwardRefExoticComponent} LucideIcon\n */\nconst DynamicIcon = forwardRef<SVGSVGElement, DynamicIconComponentProps>(\n ({ name, fallback: Fallback, ...props }, ref) => {\n const [iconData, setIconData] = useState<LucideIconData>();\n\n useEffect(() => {\n getIconData(name)\n .then(setIconData)\n .catch((error) => {\n console.error(error);\n });\n }, [name]);\n\n if (iconData == null) {\n if (Fallback == null) {\n return null;\n }\n\n return createElement(Fallback);\n }\n\n return createElement(Icon, {\n ref,\n ...props,\n icon: iconData,\n });\n },\n);\n\nexport default DynamicIcon;\n"],"names":[],"mappings":";;;;;;;;;;;;;AAcO;AAOP;AACE;AACE;AAAsE;AAIxE;AAEA;AACE;AAAY;AAGd;AACF;AAkBA;AAAoB;AAEhB;AAEA;AACE;AAGI;AAAmB;AACpB;AAGL;AACE;AACE;AAAO;AAGT;AAA6B;AAG/B;AAA2B;AACzB;AACG;AACG;AACP;AAEL;;"}