In this new era of customer and employee engagement, the ability of rating things, services, and people is everywhere. So I thought it would be useful to create a rating component for Lightning.
Rating components are sometimes implemented by swapping images to represent the star’s selected and unselected state. Using SVG is a more elegant and flexible solution: not only because the stars will scale naturally to any size without pixelation, but also because you have full programatic access to the vector paths. For example, you can programmatically change the fill color of the star, manipulate its opacity, change its stroke width and color, etc. You can expose these vector styles as attributes to create a very versatile Lightning Component. For example, the component shared in this article can be used like this:
<c:Rating colorOn="#00A1E0" colorOff="#EEEEEE"/>
<c:Rating colorOn="#64E000" stroke="#000000" strokeWidth="3"/>
The rating component also provides a good example of defining a Component Event so that the component’s user can register an event handler like this:
To make this work:
- Create a lightning event of type component named RatingChangeEvent and implemented as follows:
<aura:event type="COMPONENT"> <aura:attribute name="rating" type="integer"/> </aura:event>
- In the Rating component, register the event like this (indicating that the component may fire this event and that an event handler can be attached using an attribute named change):
<aura:registerEvent name="change" type="c:RatingChangeEvent"/>
- In the component or app using the Rating component, register an event handler like this:
As an example, I added the rating component to the recruiting app I shared yesterday. Check out the end result in this video:
Installation and Source Code
Follow the steps below to install the application in your own org:
- Enable Lightning Components in your new Developer Org: In Setup, click Develop > Lightning Components, check the Enable Lightning Components checkbox, and click Save.
- Click this link to install the application using an unmanaged package, then click Continue, Next, Next, Install.
- Open the Developer Console
- Click File > Open Lightning Resources in the menu, select RatingTestApp > APPLICATION in the dialog, and click the Open Selected button
- Click Preview in the code editor (upper right corner)
At the time of this writing, there is a bug that prevents you from using the <svg> tag in the component definition. The simple workaround is to define the svg content in a text node, and to use the component’s renderer to grab that text representation and inject it as actual svg. See the Rating component for the details.