Everything you need as a full stack developer

Building a weather widget UI that fetches data from an API

- Posted in Frontend Developer by

TL;DR To build a simple weather widget UI with React, start by setting up a new project using Node.js and Create React App, then install axios for API requests. Create a WeatherWidget component that fetches current and forecasted weather data from the OpenWeatherMap API, handle errors securely with environment variables, and run the application on localhost:3000 to display the widget in action.

Building a Weather Widget UI that Fetches Data from an API

As developers, we often find ourselves working on projects that require fetching data from external APIs. In this article, we'll be building a simple weather widget UI that fetches current and forecasted weather data from the OpenWeatherMap API.

Step 1: Setting Up Our Project

To get started, let's set up our project using Node.js as our backend framework and React for our frontend. We'll also use Create React App to scaffold our frontend project quickly and easily.

npx create-react-app weather-widget

Next, we'll install the required packages for making API requests:

npm install axios

Step 2: Creating Our Weather Widget UI

Now that our project is set up, let's start building our weather widget UI. We'll create a new component called WeatherWidget.js in the src directory.

In this component, we'll define two main sections:

  • Current Weather: This section will display the current temperature, humidity, and conditions.
  • Forecast: This section will display a list of forecasted weather data for the next 5 days.

Here's how our WeatherWidget.js file might look like:

import React from 'react';
import axios from 'axios';

const API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY'; // Replace with your own API key

class WeatherWidget extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentWeather: {},
            forecast: []
        };
    }

    componentDidMount() {
        axios.get(`http://api.openweathermap.org/data/2.5/weather?q=London&appid=${API_KEY}&units=metric`)
            .then(response => {
                this.setState({ currentWeather: response.data });
                axios.get(`http://api.openweathermap.org/data/2.5/forecast?q=London&appid=${API_KEY}&units=metric`)
                    .then(forecastResponse => {
                        this.setState({ forecast: forecastResponse.data.list });
                    })
                    .catch(error => console.error(error));
            })
            .catch(error => console.error(error));
    }

    render() {
        return (
            <div>
                <h1>Current Weather</h1>
                <p>Temperature: {this.state.currentWeather.main.temp}°C</p>
                <p>Humidity: {this.state.currentWeather.main.humidity}%</p>
                <p>Conditions: {this.state.currentWeather.weather[0].description}</p>

                <h2>Forecast</h2>
                <ul>
                    {
                        this.state.forecast.map((forecast, index) => (
                            <li key={index}>
                                <p>Date: {new Date(forecast.dt * 1000).toLocaleDateString()}</p>
                                <p>Temperature: {forecast.main.temp}°C</p>
                                <p>Humidity: {forecast.main.humidity}%</p>
                            </li>
                        ))
                    }
                </ul>
            </div>
        );
    }
}

export default WeatherWidget;

Step 3: Integrating Our API Key

In the code above, we've hard-coded our OpenWeatherMap API key. In a real-world scenario, you should never expose your API keys in your frontend code. Instead, you can use environment variables to store them securely.

Here's how you can do it:

echo "REACT_APP_OPENWEATHERMAP_API_KEY=YOUR_API_KEY" >> .env

Then, you can access the environment variable in your code like this:

import { REACT_APP_OPENWEATHERMAP_API_KEY } from 'react-app-env';

const API_KEY = process.env.REACT_APP_OPENWEATHERMAP_API_KEY;

Step 4: Running Our Application

Finally, let's run our application using npm start. Open your browser and navigate to http://localhost:3000 to see the weather widget in action.

Congratulations! You've just built a simple weather widget UI that fetches data from an API. This is just a basic example, but you can customize it further by adding more features like location selection or animation effects.

Conclusion

In this article, we learned how to build a simple weather widget UI using React and the OpenWeatherMap API. We covered setting up our project, creating our weather widget UI, integrating our API key, and running our application.

Remember, building a real-world application involves much more than just fetching data from an API. It requires careful consideration of user experience, performance optimization, security measures, and scalability.

We hope you enjoyed this tutorial! If you have any questions or want to see more examples like this, feel free to ask in the comments below.

Key Use Case

Here is a use-case for a meaningful example of something that could be put into practice based on the blog article:

Use-Case:

A company, "GreenLife", wants to integrate a weather widget on its website to provide users with relevant and timely information about the current and forecasted weather conditions. This will help users plan their daily activities more effectively and make informed decisions about their outdoor plans.

To achieve this, GreenLife can follow the steps outlined in the blog article, setting up a React project, installing required packages, creating a WeatherWidget component that fetches data from the OpenWeatherMap API, integrating the API key securely using environment variables, and running the application on a local server.

Finally

The weather widget UI built in this article is a great starting point for any project that requires fetching data from an external API. The OpenWeatherMap API provides a wealth of information about current and forecasted weather conditions, making it an ideal choice for projects like GreenLife's website. By following the steps outlined in the article, developers can easily integrate a customizable and responsive weather widget into their applications, enhancing user experience and providing valuable insights about the weather.

Recommended Books

  • "The Hitchhiker's Guide to the Galaxy" by Douglas Adams is a humorous science fiction series that explores the misadventures of human Arthur Dent as he travels through space.
  • "Sapiens: A Brief History of Humankind" by Yuval Noah Harari offers a comprehensive and thought-provoking history of humankind, covering our species' evolution, development of complex societies, and impact on the planet.
  • "The Power" by Naomi Alderman is a speculative fiction novel that explores a world where women suddenly develop the ability to release electrical jolts from their fingertips, allowing them to dominate and control society.
Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more