DEV Community

Mali Gaurav
Mali Gaurav

Posted on

Guide: Creating a Weather App with React and OpenWeatherMap API

In this guide, I'll walk you through the process of building a weather app using React and integrating the OpenWeatherMap API. We'll cover setting up your project, making API requests, displaying weather information, and adding styling using Tailwind CSS.

Note: You'll need Node.js and npm (Node Package Manager) installed on your machine before you begin.

Table of Contents

  1. Prerequisites
  2. Setting Up Your Project
  3. Getting OpenWeatherMap API Key
  4. Making API Requests
  5. Creating React Components
  6. Styling with Tailwind CSS

Prerequisites

Before you start, ensure you have the following:

  • Node.js and npm installed on your machine.
  • Basic understanding of React.js and npm packages.
  • An OpenWeatherMap API key, which you can obtain by signing up on the OpenWeatherMap website.

Setting Up Your Project

  1. Create a new React app using Create React App. Open your terminal and run:
   npx create-react-app weather-app
Enter fullscreen mode Exit fullscreen mode
  1. Navigate to your project directory:
   cd weather-app
Enter fullscreen mode Exit fullscreen mode
  1. Start your development server:
   npm start
Enter fullscreen mode Exit fullscreen mode

Your React app should now be running at http://localhost:3000.

Getting OpenWeatherMap API Key

  1. Visit the OpenWeatherMap website (https://openweathermap.org/) and sign up for an account.
  2. Once signed in, navigate to your API keys section and generate a new API key.
  3. Be sure to read and follow OpenWeatherMap's terms of use.

Making API Requests

  1. Install the axios library for handling HTTP requests:
   npm install axios
Enter fullscreen mode Exit fullscreen mode
  1. Create a new file, e.g., openWeatherMap.js, in the src directory to manage your API requests:
   // src/openWeatherMap.js
   import axios from 'axios';

   const API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY';
   const BASE_URL = 'https://api.openweathermap.org/data/2.5';

   export const fetchWeather = async (city) => {
     try {
       const response = await axios.get(`${BASE_URL}/weather?q=${city}&appid=${API_KEY}`);
       return response.data;
     } catch (error) {
       console.error('Error fetching weather:', error);
     }
   };
Enter fullscreen mode Exit fullscreen mode
  1. Import the fetchWeather function into your main App.js file and use it to fetch weather data.

Creating React Components

  1. Create a new component to display weather information:
   // src/components/Weather.js
   import React, { useState } from 'react';
   import { fetchWeather } from '../openWeatherMap';

   const Weather = () => {
     const [city, setCity] = useState('');
     const [weatherData, setWeatherData] = useState(null);

     const handleFetchWeather = async () => {
       const data = await fetchWeather(city);
       setWeatherData(data);
     };

     return (
       <div className="container mx-auto">
         <h1 className="text-3xl font-bold mb-4">Weather App</h1>
         <div className="mb-4">
           <input
             type="text"
             placeholder="Enter city"
             className="border p-2"
             value={city}
             onChange={(e) => setCity(e.target.value)}
           />
           <button className="bg-blue-500 text-white p-2 ml-2" onClick={handleFetchWeather}>
             Get Weather
           </button>
         </div>
         {weatherData && (
           <div className="border p-4 rounded shadow">
             <h2 className="text-xl font-bold mb-2">{weatherData.name}</h2>
             <p>Temperature: {weatherData.main.temp}°C</p>
             <p>Weather: {weatherData.weather[0].description}</p>
           </div>
         )}
       </div>
     );
   };

   export default Weather;
Enter fullscreen mode Exit fullscreen mode
  1. Import and use the Weather component in your App.js:
   // src/App.js
   import React from 'react';
   import Weather from './components/Weather';

   function App() {
     return (
       <div className="App">
         <Weather />
       </div>
     );
   }

   export default App;
Enter fullscreen mode Exit fullscreen mode

Styling with Tailwind CSS

  1. If you haven't already, follow the steps in the previous guide to install and configure Tailwind CSS for your project.

  2. In your Weather.js component, apply Tailwind CSS classes to style the elements:

   // src/components/Weather.js
   // ... (previous code)

   const Weather = () => {
     // ...

     return (
       <div className="container mx-auto mt-8">
         <h1 className="text-3xl font-bold mb-4">Weather App</h1>
         <div className="flex mb-4">
           <input
             type="text"
             placeholder="Enter city"
             className="border p-2 rounded-l"
             value={city}
             onChange={(e) => setCity(e.target.value)}
           />
           <button className="bg-blue-500 text-white p-2 rounded-r" onClick={handleFetchWeather}>
             Get Weather
           </button>
         </div>
         {weatherData && (
           <div className="border p-4 rounded shadow">
             <h2 className="text-xl font-bold mb-2">{weatherData.name}</h2>
             <p>Temperature: {weatherData.main.temp}°C</p>
             <p>Weather: {weatherData.weather[0].description}</p>
           </div>
         )}
       </div>
     );
   };

   // ...
Enter fullscreen mode Exit fullscreen mode
  1. Restart your development server to apply the Tailwind CSS styles.

Congratulations! You've successfully built a weather app using React and integrated the OpenWeatherMap API. Your app should now allow users to enter a city and display weather information for that city.

Remember to replace 'YOUR_OPENWEATHERMAP_API_KEY' with your actual OpenWeatherMap API key in the openWeatherMap.js file.

DEMO

Top comments (0)