Building a Weather App with React and APIs

Building a Weather App with React and APIs

Creating a weather application is a great way to practice integrating third-party APIs with React. In this article, we will build a simple weather app using React and the OpenWeatherMap API. We will cover fetching data from the API, managing state, and displaying the weather information to the user.

Prerequisites

Before we start, make sure you have the following installed on your machine:

  • Node.js and npm
  • Create React App CLI

Setting Up the React Application

First, let’s create a new React application:

npx create-react-app weather-app
cd weather-app

Getting API Key

Sign up for a free API key at OpenWeatherMap. This key will allow us to fetch weather data.

Creating the Weather Component

Create a new component called Weather.js in the src directory:

import React, { useState } from 'react';
import axios from 'axios';

const Weather = () => {
  const [city, setCity] = useState('');
  const [weather, setWeather] = useState(null);
  const [error, setError] = useState(null);

  const fetchWeather = async () => {
    const API_KEY = 'YOUR_API_KEY';
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;

    try {
      const response = await axios.get(url);
      setWeather(response.data);
      setError(null);
    } catch (err) {
      setError('City not found');
      setWeather(null);
    }
  };

  const handleChange = (e) => {
    setCity(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    fetchWeather();
  };

  return (
    <div>
      <h1>Weather App</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={city}
          onChange={handleChange}
          placeholder="Enter city"
        />
        <button type="submit">Get Weather</button>
      </form>
      {error && <p>{error}</p>}
      {weather && (
        <div>
          <h2>{weather.name}</h2>
          <p>{weather.weather[0].description}</p>
          <p>Temperature: {weather.main.temp}°C</p>
          <p>Humidity: {weather.main.humidity}%</p>
          <p>Wind Speed: {weather.wind.speed} m/s</p>
        </div>
      )}
    </div>
  );
};

export default Weather;

In this component, we use the useState hook to manage the city input, weather data, and potential error messages. The fetchWeather function fetches weather data from the OpenWeatherMap API using the axios library. If the city is found, the weather data is stored in the weather state; otherwise, an error message is displayed.

Displaying the Weather Component

Now, let’s display the Weather component in our main App.js file:

import React from 'react';
import Weather from './Weather';

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

export default App;

Styling the Weather App

Let’s add some basic styles to make our weather app look better. Create a Weather.css file in the src directory:

.weather-container {
  text-align: center;
  margin-top: 50px;
}

form {
  margin-bottom: 20px;
}

input {
  padding: 10px;
  font-size: 16px;
  margin-right: 10px;
}

button {
  padding: 10px;
  font-size: 16px;
}

.weather-info {
  border: 1px solid #ccc;
  padding: 20px;
  display: inline-block;
  margin-top: 20px;
}

Import this CSS file into Weather.js:

import './Weather.css';

Update the JSX in Weather.js to use these styles:

return (
  <div className="weather-container">
    <h1>Weather App</h1>
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={city}
        onChange={handleChange}
        placeholder="Enter city"
      />
      <button type="submit">Get Weather</button>
    </form>
    {error && <p>{error}</p>}
    {weather && (
      <div className="weather-info">
        <h2>{weather.name}</h2>
        <p>{weather.weather[0].description}</p>
        <p>Temperature: {weather.main.temp}°C</p>
        <p>Humidity: {weather.main.humidity}%</p>
        <p>Wind Speed: {weather.wind.speed} m/s</p>
      </div>
    )}
  </div>
);

Running the Application

Now that we have our component and styles set up, let’s run the application:

npm start

Open your browser and navigate to http://localhost:3000. You should see a simple weather application where you can enter a city name and get the current weather information.

Conclusion

In this article, we built a weather application using React and the OpenWeatherMap API. We covered setting up a React project, fetching data from an API, managing state, and styling the application. This project is a great starting point for exploring more advanced features and enhancements, such as adding more detailed weather data, implementing caching for API requests, or using a more sophisticated state management library like Redux.

Hashtags

#React #JavaScript #WebDevelopment #API #OpenWeatherMap #WeatherApp #Frontend #Coding #Programming #TechBlog #SoftwareDevelopment #ReactJS #WebApp #FrontendDevelopment #CodingProjects

Leave a Reply