Richard77
Richard77

Reputation: 21661

Icomoon, open-iconic SVG icons not displaying in the blazor page

I'm trying to use Icomoon in my blazor project. I've already downloaded the icons.

HTML

<button class="search__button">               
    <svg class="search__button__icon">
         <use xlink:href="img/icons/symbol-defs.svg#magnifying-glass.svg"></use>
    </svg>
</button>

CSS

.search__button {
   &__icon {
    color: #444444;
    width: 1.75rem;
    height: 1.75rem;
  }
}

The location of the SVG files

enter image description here

The result I'm getting

enter image description here

Am I missing something? I think to have followed what it's said in the documentation.

Thanks for helping

EDIT

In this documentation is says that the svg icon can be used as an image like this:

<img class="nav__level-item__icon" src="img/icons/svg/home.svg" alt="home">

When used like this, it's displaying.

&__icon {
    width: 1.75rem;
    height: 1.75rem;
    fill: #fff; //and/or color: #fff
}

The only problem with using it as an image is that I can't style it. So, at the end, I'm still stuck.

EDIT 2

I tried to implement what's suggested in this blog post. Icons are being displayed, I can't still style them.

Upvotes: 2

Views: 2339

Answers (1)

Andy Braham
Andy Braham

Reputation: 10171

According to Microsoft SVG use is a still limited, in this Microsoft document it states

If you place an <svg> tag directly into a component file (.razor), basic image 
rendering is supported but many advanced scenarios aren't yet supported. For 
example, <use> tags aren't currently respected

If you use a string variable for the xlink:href attribute the icon will render after pre-rendering but would disappear as soon as the Blazor library was loaded in the client, but looks like there is a workaround.

Instead of putting the svg and use tags in the .razor file you can return a MarkupString instead, something like

<i class="icon">
    @IconMarkupString
</i>

@code {
    [Parameter]
    public string IconSprite { get; set; }

    private MarkupString IconMarkupString
    {
        get => new MarkupString($"<svg class='icon-sprite'><use xlink:href='{IconSprite}'/></svg>");
    }
}

Then used like

<SVGIcon IconSprite="img/icons/symbol-defs.svg#magnifying-glass" />

One thing that I did notice was in order to get the styling to work on the SVG element itself I had to add a separate class to the SVG tag otherwise the styling would not be applied even when using ::deep.

Upvotes: 3

Related Questions