Loading SVGs with SVGLoader wrapped in a function

Hello, I would like to load multiple SVGs as shapes with SVGLoader (in React). The following code works (even with multiple SVGs, I need to call loader.load multiple times)

import clusterIcon from './path/to/svgfile.svg'

const loader = new SVGLoader()

let clusterGeometry = new ShapeGeometry()

loader.load(clusterIcon, (data) => {
  const paths = data.paths
  const shapes = paths
    .filter((p) => p.userData.style.fill && p.userData.style.fill !== 'none')
    .map((p) => SVGLoader.createShapes(p))
    .flat()
  clusterGeometry = new ShapeGeometry(shapes)
})

const ComponentName = () => {
  const geometry = clusterGeometry 
  const color = '#000000'

  const material = new SpriteMaterial({ color: color })
  const clusterSprite = new Sprite(material)
  clusterSprite.geometry = geometry

  return clusterSprite
}

But there are multiple SVGs, to make code clean I would like to wrap the common part into a function and reuse that part of the code

import icon1 from './path/to/svgfile.svg'
import icon2 from './path/to/svgfile.svg'

const loader = new SVGLoader()

const loadIcon = (icon) => {
  const loader = new SVGLoader()
  loader.load(icon, (data) => {
    const paths = data.paths
    const shapes = paths
      .filter((p) => p.userData.style.fill && p.userData.style.fill !== 'none')
      .map((p) => SVGLoader.createShapes(p))
      .flat()
    const geometry = new ShapeGeometry(shapes)
    return geometry
  })
}

const geometry1 = loadIcon(icon1)
const geometry2 = loadIcon(icon2)

const ComponentName = (iconNumber) => {
  const geometry = iconNumber === 1 ? geometry1 : geometry2
  const color = '#000000'

  const material = new SpriteMaterial({ color: color })
  const clusterSprite = new Sprite(material)
  clusterSprite.geometry = geometry

  return clusterSprite
}

Then this no longer works with error


What could cause this?

Your loadIcon() function always returns undefined. Keep in mind that SVGLoader.load() works asynchronously. You have to rewrite your code to honor that circumstance.

Besides, there is no need to create an instance of SVGLoader per invocation of loadIcon(). Create a single instance outside of the function and reuse it.