R

Build a Weather App in 10 Minutes Using React and OpenWeatherMap API

PinoyFreeCoder
Fri Nov 22 2024
PinoyFreeCoder
Fri Nov 22 2024

Build a Weather App in 10 Minutes Using React and OpenWeatherMap API

Building a weather app in React is an excellent project for beginners to learn about APIs, React hooks, and basic component design. In this tutorial, we'll create a simple weather app using the OpenWeatherMap API. You'll see how easy it is to fetch data from an external API and display it dynamically in a React application.

1. Set Up Your React Project

First, set up a new React project. You can use Create React App for a quick start:


      npx create-react-app weather-app
      cd weather-app
      npm start
      

2. Get Your OpenWeatherMap API Key

Create an account on the OpenWeatherMap website. Generate an API key from the API section.

3. Create a Simple UI

Let's create a basic structure for our weather app:


      // src/App.js
      import React, { useState } from 'react';
  
      const App = () => {
        const [city, setCity] = useState('');
        const [weather, setWeather] = useState(null);
  
        const fetchWeather = async () => {
          const apiKey = 'YOUR_API_KEY';
          const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`);
          const data = await response.json();
          setWeather(data);
        };
  
        return (
          

Weather App

setCity(e.target.value)} /> {weather && (

{weather.name}

{weather.main.temp}°C

{weather.weather[0].description}

)}
); }; export default App;

4. Style Your Weather App

Add some CSS for a better visual appeal. Create a src/App.css file:


      body {
        font-family: Arial, sans-serif;
        background: #f0f4f7;
        margin: 0;
      }
      input {
        padding: 10px;
        margin: 10px 0;
      }
      button {
        padding: 10px 20px;
        background: #007BFF;
        color: #fff;
        border: none;
        cursor: pointer;
      }
      

5. Run Your Weather App

Save your changes and run the app using:


      npm start
      

Now you can enter a city name, click the button, and view the current weather for that location!

Conclusion

In just a few steps, you've built a functional weather app using React and the OpenWeatherMap API. This project demonstrates how to work with APIs, manage state in React, and handle asynchronous data fetching. Where will you take this app next? Add features like 5-day forecasts or hourly weather updates!