You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This has perf consequences, but I'd do this for something like an electron or react native app, where bundle size is not an issue and the simplicity is nicer.
Another way (for which the exact details depend on your build tools and specific environment) is with dynamic imports, using code-splitting and Suspense to lazily import icons as needed. This example works with React + Vite:
import{lazy,Suspense}from'react';importtype{IconProps}from'@phosphor-icons/react';// This is essentially a map of relative paths to dynamic import functions,// but since we use named exports we need to transform them to default exports.// Most bundlers don't support template strings in dynamic imports, so we essentially// let it code-split the whole Phosphor lib and allow them to be loaded at runtime.constimportMap=Object.entries(import.meta.glob("../node_modules/@phosphor-icons/react/dist/ssr/*.mjs")).reduce((acc,[path,fn])=>{acc[path]=(name)=>fn().then((mod)=>({default: mod[name]}));returnacc;},{});functionrelativePathForIcon(name: string){return`../node_modules/@phosphor-icons/react/dist/ssr/${name}.mjs`;}exportfunctionLazyIcon(props: IconProps&{name: string}){const{ name, ...iconProps}=props;constIcon=lazy(()=>importMap[relativePathForIcon(name)](name));return(<Suspensefallback={null}><Icon{...iconProps}/></Suspense>);}// THEN IN YOUR APPfunctionApp(){return<LazyIconname="Avocado"weight="fill"color="darkolivegreen"/>;}
How can I dynamically render icons in React based on a string value?
The text was updated successfully, but these errors were encountered: