Estoy usando React con TypeScript y tengo 5 íconos SVG en un directorio que puedo importar como
import * as OtherIconsGroup from '../src/other-icons';Entonces puedo hacer referencia a cada icono como
<OtherIconsGroup.Loading fill={fillColor} width={size} height={size} /> <OtherIconsGroup.Like fill={fillColor} width={size} height={size} /> <OtherIconsGroup.Copy fill={fillColor} width={size} height={size} /> etc...El problema ahora es que necesito agregar más de 30 íconos a este directorio y estoy buscando una manera de representar dinámicamente todos los componentes, algo esencialmente como
{Object.keys(OtherIconsGroup).map(icon => { return( <OtherIconsGroup.{icon} fill={fillColor} width={size} height={size} /> ) }Obviamente, esto no funciona, así que estoy tratando de entender cómo puedo definir un componente, darle un nombre personalizado y devolverlo.
{Object.keys(OtherIconsGroup).map(icon => { const IconComponent = `OtherIconsGroup.${icon}`; return( <IconComponent fill={fillColor} width={size} height={size}/> ) }Recibo el siguiente error al agregar los accesorios anteriores, por lo que busco ayuda para definir el componente correctamente en TypeScript para poder agregar atributos de elementos SVG.
Type '{ fill: string; width: number; height: number; }' is not assignable to type 'IntrinsicAttributes'. Property 'fill' does not exist on type 'IntrinsicAttributes'.ts(2322)¡En realidad estás muy cerca! Solo problemas menores de sintaxis con JSX.
Se podría hacer así:
const icons = Object.entries(OtherIconsGroup) .map(([_, Icon]) => <Icon fill={fillColor} width={size} height={size}/>);o
const icons = Object.map(OtherIconsGroup) .map((iconName) => { const Icon = OtherIconsGroup[iconName]; return <Icon fill={fillColor} width={size} height={size}/>; });