Guide: Creating a Weather App with React and OpenWeatherMap API
Tags: react, api, weatherapp, webdev
Published: 2023-08-19 13:14:08

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](#prerequisites)
2. [Setting Up Your Project](#setting-up-your-project)
3. [Getting OpenWeatherMap API Key](#getting-openweathermap-api-key)
4. [Making API Requests](#making-api-requests)
5. [Creating React Components](#creating-react-components)
6. [Styling with Tailwind CSS](#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:

   ```bash
   npx create-react-app weather-app
   ```

2. Navigate to your project directory:

   ```bash
   cd weather-app
   ```

3. Start your development server:

   ```bash
   npm start
   ```

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:

   ```bash
   npm install axios
   ```

2. Create a new file, e.g., `openWeatherMap.js`, in the `src` directory to manage your API requests:

   ```jsx
   // 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);
     }
   };
   ```

3. 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:

   ```jsx
   // 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;
   ```

2. Import and use the `Weather` component in your `App.js`:

   ```jsx
   // src/App.js
   import React from 'react';
   import Weather from './components/Weather';

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

   export default App;
   ```

## 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:

   ```jsx
   // 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>
     );
   };

   // ...
   ```

3. 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](https://maligaurav947.github.io/react-weather-app/)