I am getting below error while trying to render custom SVG in LWC
[Failed to execute 'setAttributeNS' on 'Element': 'http://www.w3.org/1999/xlink' is an invalid namespace for attributes.]
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityI am getting below error while trying to render custom SVG in LWC
[Failed to execute 'setAttributeNS' on 'Element': 'http://www.w3.org/1999/xlink' is an invalid namespace for attributes.]
Here is the link from lwc documentation on how to do it.
// myComponent.js
import { LightningElement } from 'lwc';
import SVG_URL from '@salesforce/resourceUrl/svg_url';
export default class myComponent extends LightningElement {
get svgURL {
return SVG_URL;
}
}
<!-- myComponent.html -->
<template>
<svg xmlns="http://www.w3.org/2000/svg">
<use xlink:href={svgURL}></use>
</svg>
</template>
None of the answers here really provide a complete solution to the issue most people likely have when they searched this.
If you are trying to use a custom SVG within Lightning Web Components, not as the icon for the Component itself in the builder, this answer is for you.
In order to use svg in the <use>
tag of the svg as you see in all the examples, you must first make sure your svg file has a <g>
tag wrapped around all of the content you wish to use and that tag needs an id.
Rather than just returning the url returned by importing the resource, append the id to the end like so
get svgURL() {
return SVG_URL + '#layer1';
}
You can then reference this getter method in one of these two ways:
<!-- Option 1 -->
<lightning-icon src={svgURL}></lightning-icon>
<!-- Option 2 -->
<svg xmlns="http://www.w3.org/2000/svg">
<use xlink:href={svgURL}></use>
</svg>
This is from the documentation for <lightning-icon>
Chances are the aspect ratio/viewbox of your svg image won't match what <lightning-icon>
uses, and if that's the case use Option two and specify the same viewbox as the custom svg file on the new svg
tag.
For more information on viewbox and svg scaling, (here)[https://stackoverflow.com/a/19485375/9565551] is a lovely answer about it.
<g>
you are referencing. Give it a different id and change the color here. Then you can use your JS code to switch between which reference is being used. Make sense?
Mar 30, 2020 at 17:55
<img>
tag to display icon in the IE. It works but I didn't find any solution to change the color. Anyway, it is enough for now. Thanks for your answer, it is cool if you don't have to support IE ;)
I am using icon-name to render custom svg, and it works fine:
<template>
<lightning-card title="Account Dashboard" icon-name="custom:custom19">
<div class="slds-m-around_medium">
<svg class="d3" width={svgWidth} height={svgHeight} lwc:dom="manual"></svg>
</div>
</lightning-card>
</template>