LWC components with self contained images
When you create your LWC components, it is easy to include Salesforce predefined icons using lightning-icon
. However once you need a custom icon, you point to an external URL, breaking the self containment. Unless you use url(data:)
. Here is what I did
A scalable check mark
For a list selection component I wanted a green check mark, like the picture above, indicate a selected record (more on the component in a later post). Since LWC doesn't allow (yet?) to store image assets inside a bundle and I wanted the component to be self contained.
The solution is to use data:image/svg+xml
for a background image. The details were nicely outlined in css-tricks. I tried to use svg as source code directly, but failed to get it to work. So I resorted to use base64
. It is an additional step, using an online Base64 encoder.
Making images
SVG is just an XML based text format, so you could create your image in notepad (take that jpg!). However you probably want to use a graphic editor. My choice here is Sketch (which gives me funny looks from designers: why a developer uses one of their tools). There were some steps worth to mention:
- When using text (like the check mark), convert that to a svg path. Right click on text and select "Convert to outlines". This allows the text to scale with the rest of the image
- Use the Edit-Copy-Copy SVG Code rather than use the export functionality
- The resulting SVG is "talkative", you can edit and remove quite some content:
- remove width and height attributes from the
<svg>
element, but keep the viewbox. Also remove the xlink name space - the
<g>
element doesn't need any attribute <polygon>
only needsfill
andpoints
attribute- All numeric values have many digits. You can round them up
Read more
Posted by Stephan H Wissel on 18 April 2019 | Comments (0) | categories: Lightning Salesforce