How To Make Weather App Using React JS 2024 | Weather API React Project Tutorial

3 min read 2 hours ago
Published on Nov 01, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will create a Weather App using React JS and the OpenWeatherMap API. This app allows users to enter a city, state, or country and receive accurate weather data, including temperature, humidity, wind speed, and weather conditions. By following these step-by-step instructions, you'll gain practical experience in React and API integration.

Step 1: Setup React Project

  1. Install Node.js: Ensure you have Node.js installed on your machine. You can download it from nodejs.org.
  2. Create a new React application:
    • Open your terminal and run:
      npx create-react-app weather-app
      
    • Navigate to the project directory:
      cd weather-app
      
  3. Install Axios: This library will help us make API requests.
    • Run the following command in your terminal:
      npm install axios
      

Step 2: Create Weather App UI

  1. Open the project in your code editor.
  2. Modify the App.js file:
    • Clear the default content and set up the basic structure for the Weather App.
    • Here’s a simple example of how your App.js might look:
      import React, { useState } from 'react';
      import './App.css';
      
      function App() {
          const [city, setCity] = useState('');
          const [weatherData, setWeatherData] = useState(null);
      
          return (
              <div className="App">
                  <h1>Weather App</h1>
                  <input 
                      type="text" 
                      placeholder="Enter city" 
                      value={city} 
                      onChange={(e) => setCity(e.target.value)} 
                  />
                  <button onClick={fetchWeather}>Get Weather</button>
                  {weatherData && <WeatherDisplay data={weatherData} />}
              </div>
          );
      }
      
      export default App;
      
  3. Create a WeatherDisplay component to show the fetched weather data.

Step 3: Add OpenWeatherMap API

  1. Sign up for an API key:
  2. Fetch weather data:
    • In the fetchWeather function, use Axios to make a GET request to the OpenWeatherMap API:
      const fetchWeather = () => {
          const apiKey = 'YOUR_API_KEY';
          axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)
              .then(response => {
                  setWeatherData(response.data);
              })
              .catch(error => {
                  console.error('Error fetching the weather data:', error);
              });
      };
      
  3. Handle API responses: Ensure to handle errors and display appropriate messages when the city is not found.

Step 4: Create Search Feature

  1. Enhance user experience:
    • Allow users to press "Enter" to fetch weather data.
    • Update the input field to call fetchWeather on key press:
      <input 
          type="text" 
          placeholder="Enter city" 
          value={city} 
          onChange={(e) => setCity(e.target.value)} 
          onKeyPress={(e) => e.key === 'Enter' && fetchWeather()} 
      />
      
  2. Display the weather information:
    • In the WeatherDisplay component, format and display temperature, humidity, wind speed, and weather condition based on the data received from the API.

Conclusion

You have successfully built a Weather App using React JS and the OpenWeatherMap API. You learned how to set up a React project, create a user interface, fetch data from an API, and display that data dynamically. As a next step, consider enhancing your app by adding features such as a loading indicator, error handling, or even a 5-day forecast functionality. Happy coding!