Crafting a Customizable Weather Widget With Web Components
The guide explains how to build a customizable weather widget using Web Components, featuring city selection, real-time weather data display, and dynamic styling.
Join the DZone community and get the full member experience.
Join For FreeWeather widgets are a common sight on many websites and applications. They provide users with a quick glance at the weather conditions for a specific location. But what if you could create your own customizable weather widget that aligns perfectly with your site’s theme and also offers a chance to dive deep into the capabilities of Web Components? In this article, we’ll do just that!
Introduction
Web Components allow developers to create reusable and encapsulated custom elements. Our goal will be to build a weather widget that:
- Fetches and displays weather data based on a selected city.
- Offers slots for customization, such as adding a custom title or footer.
- Dynamically updates its styles based on the weather conditions.
Designing the Weather Widget
Our widget will have the following sections:
- A title slot for customization.
- A dropdown to select a city.
- Display area for temperature, humidity, and weather condition icons.
- A footer slot for additional customization.
Implementation
1. Setting Up the Template
We’ll begin by defining the template for our component:
<template id="weather-widget-template">
<style>
/* Styles for the widget */
</style>
<slot name="title">Weather Forecast</slot>
<select class="city-selector">
<!-- City options go here -->
</select>
<div class="weather-display">
<span class="temperature"></span>
<span class="humidity"></span>
<img class="weather-icon" alt="Weather Icon">
</div>
<slot name="footer"></slot>
</template>
2. JavaScript Logic
Next, we’ll provide the logic:
class WeatherWidget extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
const template = document.getElementById('weather-widget-template');
const node = document.importNode(template.content, true);
this.shadowRoot.appendChild(node);
this._citySelector = this.shadowRoot.querySelector('.city-selector');
this._weatherDisplay = this.shadowRoot.querySelector('.weather-display');
// Event listeners and other logic...
}
connectedCallback() {
this._citySelector.addEventListener('change', this._fetchWeatherData.bind(this));
this._fetchWeatherData();
}
_fetchWeatherData() {
const city = this._citySelector.value;
// Fetch the weather data for the city and update the widget...
}
}
customElements.define('weather-widget', WeatherWidget);
3. Fetching Weather Data
For our widget to display real-time weather data, we’ll integrate with a weather API. Here’s a simplified example using the fetch
API:
_fetchWeatherData() {
const city = this._citySelector.value;
fetch(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}`)
.then(response => response.json())
.then(data => {
const { temp_c, humidity, condition } = data.current;
this.shadowRoot.querySelector('.temperature').textContent = `${temp_c}°C`;
this.shadowRoot.querySelector('.humidity').textContent = `Humidity: ${humidity}%`;
this.shadowRoot.querySelector('.weather-icon').src = condition.icon;
});
}
4. Dynamic Styling
Based on the weather conditions, we can apply dynamic styles to our widget:
// ... Inside the _fetchWeatherData function ...
.then(data => {
// ... Other data processing ...
const widgetElement = this.shadowRoot.querySelector('.weather-display');
if (temp_c <= 0) {
widgetElement.classList.add('cold-weather');
} else if (temp_c > 30) {
widgetElement.classList.add('hot-weather');
}
})
Using the Weather Widget
To use our widget in an application:
<weather-widget>
<span slot="title">My Custom Weather Title</span>
<span slot="footer">Weather data sourced from WeatherAPI</span>
</weather-widget>
Conclusion
Our customizable weather widget not only provides real-time weather updates but also showcases the capabilities of Web Components. Through this exercise, we’ve seen how to encapsulate logic and design, fetch and display dynamic data, and offer customization points using slots.
Web Components offer a future-proof way of creating versatile and reusable elements, and our weather widget is just the tip of the iceberg. Happy coding and always be prepared for the weather!
Note: Make sure to replace YOUR_API_KEY
with your actual API key if you're using the WeatherAPI or any other service. Always follow best practices to secure your API keys.
Published at DZone with permission of SUDHEER KUMAR REDDY GOWRIGARI. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments