Hicham
Hicham

Reputation: 67

Importing all files from a folder in react

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?

Upvotes: 0

Views: 9004

Answers (2)

Piyush Sinha
Piyush Sinha

Reputation: 129

You can use context here

const importAll = (r) => {
  return r.keys().map(r);
};

const allData = importAll(
  require.context("./icons", false, /\.svg$/)
)

Upvotes: 2

Sagi_Avinash_Varma
Sagi_Avinash_Varma

Reputation: 1509

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])

Upvotes: 5

Related Questions