Importing all files from a folder in react

2019-09-06 11:01发布

问题:

I am importing all SVG's from a folder in 'icons' through an index.jsx like the following line:

index.jsx:

export about from './about.svg';

Here goes the Import: Button.jsx

import React from 'react';
import './MenuIcon.scss';
import * as IconID from './icons';

const Button = (props) => {
    return (
        <div className="menu-icon" >
            <div className={'menu-icon__icon-wrapper'}>
                <IconID.about /> // This works great
                <IconID['about'] /> // This does not work
            </div>
        </div>
    );
};

export default Button;

Now to get a specific Svg e.g. I just call in the return methode and everything works fine.

Now I want to load different SVG's like:

const svgName = 'back';

return (<IconId['back'] />);

How can i make this possible?

回答1:

Use React.createElement syntax for dynamic definition of element instead of JSX, as it only works with compile-time identifiers.

React.createElement(IconId.back, {...props}, [...children])