How to import an entire folder of SVG images (or how to load them dynamically) into a React Web App?

前端 未结 5 1745
挽巷
挽巷 2021-02-05 05:02

I have a component that takes in an :itemName and spits out an html bundle containing an image. The image is different for each bundle.

Here\'s what I have:



        
5条回答
  •  轮回少年
    2021-02-05 05:37

    Stumbled onto this issue - I initially had the "Accepted answer", but i caused http request for each and every svg, which triggered a rate limit. So I ended up with a combination the accepted answer and what @karthik proposed - using a loader in the request.context

    As of CRA 2.0 @svgr is included to import svg's as react components.

    const reqSvgs = require.context('!@svgr/webpack!flag-icon-css/flags/4x3', true, /\.svg$/)
    

    So here we combine an svg loader and require.context

    const flagMap = reqSvgs.keys().reduce((images, path) => {
      const key = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'))
      images[key] = reqSvgs(path).default
      return images
    }, {})
    

    Then we map all these into a json object so we can use key lookup

    To render svg's in jsx:

    const Flag = flagMap['dk']
    return (
      
    )
    

    And happy days, svgs included in bundle and no individual http requests

提交回复
热议问题