Dynamic Icons in Lightning Components

NOTE: As of Winter ’18, API v41, all components below are available with the standard lightning:dynamicIcon componentThis post will continue to exist should anyone need to reference for making their own SVGs.


With the addition of the new Lightning:icon components, it’s great for being able to easily add the standard set of icons, such as an account Icon, a user, chevrons (that’s a fun word to say!) and more.  However, adding svgs to lightning for more advanced CSS animations and renderings still is a boon to the platform.  After thinking on how I’d go about solving this, with the dynamic icons from the lightning design system website, I’ve solved for this.

The syntax is quite simple.  Let’s take the trend down dynamic icon:

<span data-slds-trend="down" class="{!v.spanClass != '' ? v.spanClass : 'slds-icon-trend slds-is-animated'}" title="{!v.description}">
            <c:svg viewbox="0 0 16 16" childItems="[{'path' : {'class' : 'slds-icon-trend__arrow', 'd':'M.75 8H11M8 4.5L11.5 8 8 11.5'}}, 
                                                   {'circle' : {'class' :'slds-icon-trend__circle', 'cy' : '8', 'cx' : '8', 'r' : '7.375', 'transform' : 'rotate(-28 8 8) scale(-1 1) translate(-16 0)'}}]">

We wrap an SVG icon in the class directly from the SLDS website.   I’ve allowed for an override of the standard class.  You might use this to use the pause attribute or to address an idea that was brought up on the SLDS github to decouple color and trends (for example, the trend up would be bad for case times and trends down would be good).

You’ll see that the SVG component in this case takes the viewbox attribute and a childItems attribute, which is simply a json formatted string for all of the child items to render.

I’ve went ahead and rendered this for all of the standard dynamic icons. Leaving you to use them with some simple markup:

<c:dynamicIcon iconType="ellie" />
<c:dynamicIcon iconType="eq" />
<c:dynamicIcon iconType="positive" />
<c:dynamicIcon iconType="negative" />
<c:dynamicIcon iconType="strength" strengthLevel="1" />
<c:dynamicIcon iconType="strength" strengthLevel="-1" />
<c:dynamicIcon iconType="strength" spanClass="slds-icon-strength slds-is-animated" strengthLevel="1" />
<c:dynamicIcon iconType="strength" spanClass="slds-icon-strength slds-is-animated" strengthLevel="-1" />
<c:dynamicIcon iconType="trendUp" />
<c:dynamicIcon iconType="trendDown" />
<c:dynamicIcon iconType="trend" />
<c:dynamicIcon iconType="waffle" />

Want to use this simple syntax?  You can get the components here: https://github.com/jmdohn/dynamicIcons.


Leave a comment

Your email address will not be published. Required fields are marked *