How to Create a Weather App with React and OpenWeather API

In this tutorial, we will learn how to create a weather app using React and the OpenWeather API. The app will display the current weather information for a given city.

Prerequisites

To follow along with this tutorial, you will need:

  • Node.js installed on your machine
  • Basic knowledge of JavaScript and React

Step 1: Set Up the Project

Create a new directory for your project and navigate to it using the command line. Run the following command to initialize a new React project:

npx create-react-app weather-app

This will create a new directory named weather-app containing a basic React project structure.

Navigate to the project directory:

cd weather-app

Next, open the project in your preferred code editor.

Step 2: Obtain an API Key from OpenWeather

To access weather data from OpenWeather, you will need an API key. Visit the OpenWeather API website and sign up for a free account.

Once signed in, navigate to the API Keys page and copy your generated API key.

Step 3: Install Dependencies

In this step, we will install some dependencies required for our weather app.

Run the following command to install the Axios library, which we will use to make HTTP requests to the OpenWeather API:

npm install axios

Next, install the Bootstrap CSS framework to style our app:

npm install bootstrap

Step 4: Create a Weather component

Inside the src directory, create a new file named Weather.js. This component will be responsible for fetching weather information and displaying it.

Open Weather.js and import React and Axios:

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

Next, define the Weather component:

function Weather() {
  const [weatherData, setWeatherData] = useState(null);

  useEffect(() => {
    const fetchWeatherData = async () => {
      try {
        const response = await axios.get(
          `http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=YOUR_API_KEY`
        );
        setWeatherData(response.data);
      } catch (error) {
        console.error(error);
      }
    };

    fetchWeatherData();
  }, []);

  if (!weatherData) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{weatherData.name}</h1>
      Temperature: {weatherData.main.temp}ยฐC
      Weather: {weatherData.weather[0].description}
    </div>
  );
}

export default Weather;

In the above code, we are using the useState hook to manage the weather data state and the useEffect hook to fetch the weather data when the component mounts.

Replace YOUR_API_KEY with the API key you obtained from OpenWeather.

We are making a GET request to the OpenWeather API to fetch weather data for London in metric units. You can replace London in the URL with any other city name of your choice.

The weather data is stored in the weatherData state variable and displayed in the component’s JSX.

Step 5: Render the Weather component

Open src/App.js and replace the existing code with the following:

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

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

export default App;

Here, we are rendering the Weather component inside the App component. The container class is from the Bootstrap CSS framework and gives our app layout styles.

Step 6: Style the Weather component

Open src/Weather.js and import the CSS file for Bootstrap:

import 'bootstrap/dist/css/bootstrap.min.css';

This will load the Bootstrap CSS styles for our app.

Step 7: Run the app

Save all the changes and start the development server by running the following command in your project directory:

npm start

This will start the app and open it in your default browser. You should see the weather information for the specified city (London by default).

Step 8: Deploy the app (optional)

If you want to deploy your weather app to a live server, you can use services like Netlify or Vercel.

First, create a production build of your app by running the following command:

npm run build

This will create an optimized version of your app in the build directory.

Next, follow the deployment instructions provided by Netlify or Vercel to deploy your app.

Congratulations! You have successfully created a weather app using React and the OpenWeather API. You can further enhance the app by adding more features like searching for weather information for different cities.

Conclusion

In this tutorial, we learned how to create a weather app using React and the OpenWeather API. We covered how to set up the project, obtain an API key from OpenWeather, install necessary dependencies, create the main Weather component, render it in our app, style the component, and deploy the app to a live server. Feel free to modify and extend the app according to your requirements.

Related Post