Loop through components and return in switch case

2019-08-27 17:48发布

问题:

Brief description

So thanks to the svg-to-react-cli script I have 73 components for my icons. Now, if I want to call these icons, I can individually call each one I want to use. But this is not what I want.

What I want is to call only one component where I add a 'name' value to.
e.g.: < Icon name='Name of one of the 73 components I wish to call' />

My question

How do I loop through multiple components inside a directory, and return them inside a switch case?

This is how all my 73 components inside the directory look like

import React from 'react';

export default function NAMEOFICON(props) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width={100} height={100} {...props}>
      ...CONTENT OF SVG...
    </svg>
  );
}

This is what I have

import React from 'react';
import ALLCOMPONENTS from 'DIRECTORY WITH COMPONENTS'

// HERE I WANT TO LOOP THROUGH COMPONENTS AND ADD THEM IN THIS SWITCH
const getPath = (name, props) => {
  switch (name) {
    case 'NAME OF THE COMPONENT':
      ... HERE COMES CONTENT OF COMPONENT...
    default:
      return <path />;
  }
};
// HERE I CREATE A CONST TO LATER CALL THE DESIRED COMPONENT BY NAME
const Icon = ({
  name = '',
  style = {},
  fill = 'currentColor',
  viewBox = '',
  width = '20px',
  className = 'icon icon' + name,
  height = '20px'
}) => (
    {NAME OF COMPONENT({ fill })}
);

export default Icon ;

回答1:

It's incorrect to rely on directory contents in client-side script because there's none in bundled application.

A proper way is to have a 'barrel' module that re-exports all submodules:

icon-components/index.js

export { default as FooIcon } from './foo-icon';
export { default as BarIcon } from './bar-icon';

And use it like:

import * as icons from './icon-components';

...

for (const [iconComponentName, IconComponent] of Object.entries(icons)) { ... }

It makes sense to generate index.js similarly to how icon components were generated, i.e. in Node.js environment where there's an access to file system. svg-to-react-cli could be forked for this purpose, or this could be a separate script.



回答2:

One solution could be...

Have an index file that exports all your icons.

export { SomeIcon } from './someIcon.jsx';
export { SomeOtherIcon } from './someOtherIcon.jsx';

Import all the icons into Icons

import * as Icons from 'icons';

You can grab the component using the name as a key on Icons

const Icon = Icons[props.name];
return <Icon {...otherProps} />;