Developing a Weather App with Next.js


Introduction

In this tutorial, we will walk you through the process of creating a Weather App using Next.js. We'll use a weather API to fetch real-time weather data and display it in a user-friendly interface. This project will help you learn how to build a simple web application with Next.js that connects to an external API.


Setting Up the Project

Before we start, ensure you have Node.js and npm installed on your system. You can download and install them from the official website if needed.


Create a new Next.js project using the following commands:


        npx create-next-app weather-app
cd weather-app

Fetching Weather Data

To display weather information, we'll need to connect to a weather API. In this example, we'll use the OpenWeatherMap API. You'll need to sign up for an API key on their website to access their data.


Create a file for API calls, such as api/weather.js:


        const apiKey = 'YOUR_API_KEY';
const apiUrl = 'https://api.openweathermap.org/data/2.5/weather';
export async function fetchWeatherData(city) {
const response = await fetch(`${apiUrl}?q=${city}&appid=${apiKey}`);
const data = await response.json();
return data;
}

Creating Components

Components in Next.js are reusable building blocks of your application. Let's create components for displaying weather information and the main application.


        // components/Weather.js
import React from 'react';
const Weather = ({ data }) => (
<div>
<h2>Weather in {data.name}</h2>
<p>Temperature: {data.main.temp}°C</p>
<p>Weather: {data.weather[0].description}</p>
</div>
);
export default Weather;

        // pages/index.js
import React, { useState } from 'react';
import Weather from '../components/Weather';
import { fetchWeatherData } from '../api/weather';
export default function Home() {
const [city, setCity] = useState('');
const [weatherData, setWeatherData] = useState(null);
const getWeather = async () => {
try {
const data = await fetchWeatherData(city);
setWeatherData(data);
} catch (error) {
console.error('Error fetching weather data', error);
}
};
return (
<div>
<h1>Weather App</h1>
<input
type="text"
placeholder="Enter a city name"
value={city}
onChange={(e) => setCity(e.target.value)}
/>
<button onClick={getWeather}>Get Weather</button>
{weatherData && <Weather data={weatherData} />}
</div>
);
}

Conclusion

You've just created a Weather App using Next.js that fetches real-time weather data from an API. This project is a great starting point for learning Next.js and integrating external APIs into your web applications. You can enhance this app by adding more features like 5-day forecasts, location-based weather, or using different weather data sources.