Home > OS >  How to iterate over * (star) imported modules from index file
How to iterate over * (star) imported modules from index file

Time:02-16

I have build a icon libaray for a React App. I use multiple Icons form different sources (Bootstrap, Feather, etc.).

Now im writing a documentation for the libaray and I want iterate over the icons.

Structure of Lib

icons
   |- index.ts
   |- feather
         |- index.ts
         |- Icon1.tsx
         |- Icon2.tsx
   |- bootstrap
         |- index.ts
         |- Icon1.tsx
         |- Icon2.tsx

/icons/index.ts

import * as Bootstrap from './bootstrap'
import * as Feather from './feather'
export {
    Bootstrap,
    Feather
}

/icons/feather/index.ts

export { default as Icon1} from './Icon1';
export { default as Icon2} from './icon2';
...

Problem

in my documentation, i want display all icons. Now I try iterate over the star import like this:

import { Feather } from '../icons'

...

const TestView: FC = () => {

   return(
      {Object.keys(Feather).map( k => <Feather[k] />)}
                                       ^^^^^^^^^^^^
   )

}

Error message: JSX element type 'Feather' does not have any construct or call signatures.ts(2604)

Inspired by https://stackoverflow.com/a/61442894/7120013

EDIT:

in my React app, i use the icons following

import {Feather} from '../icons'

const {Icon2} = Feather


...

<Feather.Icon1 />
<Icon2 />


The Icon Component looks like:

// GENERATE BY ./scripts/build.ts
// DO NOT EDIT IT MANUALLY

import * as React from 'react'
import {ReactComponent as iconSVG} from '../../svg/feather/activity.svg';
import Icon, { IconProps } from '../../component/Icon'; 

const Activity = (
    props: IconProps,
    ref: React.ForwardedRef<HTMLSpanElement>,
    ) => 
    <Icon {...props} ref={ref} icon={
        {
            svg: iconSVG, 
            name: "activity"}
        } 
    />;

Activity.displayName = 'Activity';
export default React.forwardRef<HTMLSpanElement, IconProps>(Activity);

CodePudding user response:

Your <Feather /> component probably works like this: <Feather icon={k} /> right? Can you give more details of a normal implementation of your Feather component?

CodePudding user response:

You're pretty much there all you need to do is create a const from the Feather[k].

{Object.keys(Feather).map(k => {
    const Component = Feather[k]
    return <Component />
  })}

I can't explain why it work's that way but I do know that it works, sorry for the poor answer

  • Related