Importing all files from a folder in react
Asked Answered
P

2

0

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?

Persis answered 11/12, 2016 at 12:19 Comment(2)
Why are you using <IconID.about /> over <img src={IconID.about} />? There is nothing, technically wrong with using array accessor over properties. (jsbin.com/jesonafuto/edit?html,js,output)Demoralize
Well actually this is how the project is build and it uses github.com/jhamlet/svg-react-loader to load the svg to the browser. I have to restructure the project to load svg's this way. If there is no alternative I would use url-loader and load svg to img but if there is another option this would be nicePersis
A
5

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

Alban answered 11/12, 2016 at 13:12 Comment(0)
R
2

You can use context here

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

const allData = importAll(
  require.context("./icons", false, /\.svg$/)
)
Reneta answered 16/2, 2021 at 7:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.