Skip to content
Advertisement

Calling array object in src does not work

I have an array :

let x = '';
let elements = [
            { icon:"Home",name:'Home',page:'Page1' },
            { icon:'Cube',name:'New',page:'Page2' }];

I am looping in it:

{#each elements as { icon, name, page }, i}
                        
                        <Icon src={icon} size="24" />

This here does not work: src={icon}

Correct way should be like this:

<Icon src="{Filter}" solid />

If I replace the {icon} with string it works! Can someone tell me why? Thank you

Advertisement

Answer

The reason this doesn’t work is because <Icon src="xxx" /> does not expect a string but an object. If you import the icons from the library and log them you will see they follow the format:

{
  "default": {
    "a": {
      "fill": "none",
      "viewBox": "0 0 24 24",
      "stroke": "currentColor",
      "aria-hidden": "true"
    },
    "path": [
      {
        "stroke-linecap": "round",
        "stroke-linejoin": "round",
        "stroke-width": "2",
        "d": "M5 10l7-7m0 0l7 7m-7-7v18"
      }
    ]
  },
  "solid": {
    "a": {
      "viewBox": "0 0 20 20",
      "fill": "currentColor",
      "aria-hidden": "true"
    },
    "path": [
      {
        "fill-rule": "evenodd",
        "d": "M3.293 9.707a1 1 0 010-1.414l6-6a1 1 0 011.414 0l6 6a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L4.707 9.707a1 1 0 01-1.414 0z",
        "clip-rule": "evenodd"
      }
    ]
  }
}

So what you need to do is either import the icons and use those in your element array as another answer already mentions. Or alternatively, import all icons in your application and do something like

<Icon src={allIcons[name]} />

but then you lose tree shaking and make your bundle a lot bigger.

Advertisement