What We Built
In this example, we built a widget that gets real-time stock performance data from IEX Trading*.
How We Built It
We added six text elements to the mediaBox. One text element displays the current date. The remaining text elements are used as labels for the stock info: open, close, volume, low and high. Then, we added two vector art images—an up arrow and a down arrow. These arrows appear when a stock’s value goes up or down.
We added the following properties to our widget:
percentChangeThreshold: This numeric property is the amount of change in the stock value that will trigger the changeAlert event.
refreshInterval: This numeric property represents how frequently the stock information refreshes in the widget.
symbol: This text property determines which stock’s data is displayed in the widget.
Users will be able to set all of these properties from their widget settings.
Use an HTML template for the styling of the percentageChange text. This lets us change the color of the text to green (positive) or red (negative), depending on the stock’s change value.
When the page loads, call refresh so that the widget gets the current stock value.
When widget properties change, the widget automatically calls onPropsChanged(oldProps, newProps) with refresh() to update the widget. For example, when a user changes the stock property, we refresh the widget to display the data for that stock.
In the refresh() function, call getStockData() to create a URL that queries the IEX API and returns the results as a JSON object.
Use the processQuote() function to process the data returned from the IEX API. Set the latest stock value, company name and all other labels to their matching elements in the widget. Based on a positive or negative change in the stock value, determine if the value should be shown in red with a red down arrow, or green with a green up arrow, and provide that information for the HTML template. This function also tests it the percent change in the stock value is greater than the threshold set by the user. If it is, the function fires the changeAlert event. We can use this event to perform any action we want on the site.
Find all the information you need to get started on your next web component.