Building a Weather Forecast App with React and OpenWeatherMap API

Harshana Batagalla
4 min readJun 29, 2023

--

Introduction:

In this tutorial, we will explore how to leverage the OpenWeatherMap API to create a simple weather forecast application using React. OpenWeatherMap provides an extensive set of weather data, including current weather conditions, forecasts, and more. By integrating this API into our React application, we can display real-time weather information to our users. So, let’s dive in and learn how to connect the OpenWeatherMap API to a React application step by step.

Building a Weather Forecast App with React and OpenWeatherMap API

Prerequisites:

Before we begin, make sure you have the following prerequisites:

  1. Basic knowledge of JavaScript and React.
  2. Node.js and npm (Node Package Manager) installed on your system.
  3. A code editor of your choice (e.g., Visual Studio Code).

Step 1: Create an OpenWeatherMap Account and Generate API Key

  1. Visit the OpenWeatherMap website (https://openweathermap.org/) and click on “Sign Up” or “Log In” to create an account or log into your existing account.
  2. Once logged in, navigate to your account dashboard.
  3. From the dashboard, locate my API Keys section and click on “Create Key” or “API Keys” to generate a new API key.
  4. Provide a name for your API key (e.g., “WeatherApp”) and click on the “Generate” or “Create” button.
  5. Your API key will be generated and displayed on the screen. Make sure to copy it as we will need it later.
locate API key
Locate API key

Step 2: Set up a new React project

  1. Open your terminal or command prompt.
  2. Run the following command to create a new React project:
npm create-react-app weather-app

3. Once the project is created, navigate into the project directory:

cd weather-app

Step 3: Install required packages.

  1. In the project directory, install the necessary packages by executing the following command:
npm install axios

We will use the Axios library to make HTTP requests to the OpenWeatherMap API.

Step 4: Create a Weather component.

  1. Inside the “src” directory, create a new file called “Weather.js” and open it in your code editor.
  2. Add the following code to define a functional component named Weather:
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const Weather = () => {
const [city, setCity] = useState('');
const [weatherData, setWeatherData] = useState(null);

const fetchData = async () => {
try {
const response = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid={YOUR_API_KEY}`
);
setWeatherData(response.data);
console.log(response.data); //You can see all the weather data in console log
} catch (error) {
console.error(error);
}
};

useEffect(() => {
fetchData();
}, []);

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

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

return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter city name"
value={city}
onChange={handleInputChange}
/>
<button type="submit">Get Weather</button>
</form>
{weatherData ? (
<>
<h2>{weatherData.name}</h2>
<p>Temperature: {weatherData.main.temp}°C</p>
<p>Description: {weatherData.weather[0].description}</p>
<p>Feels like : {weatherData.main.feels_like}°C</p>
<p>Humidity : {weatherData.main.humidity}%</p>
<p>Pressure : {weatherData.main.pressure}</p>
<p>Wind Speed : {weatherData.wind.speed}m/s</p>
</>
) : (
<p>Loading weather data...</p>
)}
</div>
);
};

export default Weather;

Replace {YOUR_API_KEY} in the API URL with the API key you generated from OpenWeatherMap.

Step 5: Connect the Weather component to your app.

  1. Open the “App.js” file in the “src” directory.
  2. Replace the existing code with the following code:
import React from 'react';
import Weather from './Weather';

const App = () => {
return (
<div>
<h1>Weather Forecast App</h1>
<Weather />
</div>
);
};

export default App;

Your output should look like this:

Initial app look
Initial look
When searched a city

Step 8: Styling and additional features.

Feel free to add your preferred styling and enhance the app with additional features. You can include icons or images to represent the weather conditions or display extended forecasts.

With proper styling, you can achieve an appealing and user-friendly design like this:

Styled UI
Styled UI

Conclusion:

Congratulations! You have successfully connected the OpenWeatherMap API to your React application and built a simple weather forecast app. By following this tutorial, you have learned how to make API requests, handle the retrieved data, and display it in your React components. You have also implemented an input box where users can enter the city for which they want to retrieve weather information.

Remember to make good use of error handling, consider best practices for API requests, and explore the OpenWeatherMap API documentation for additional data and features that you can incorporate into your weather forecast application.

Feel free to enhance the app by adding more features, customizing the UI, or integrating other APIs to provide a richer user experience.

Happy coding!

--

--

Harshana Batagalla

IT undergraduate of University of Moratuwa, with a deep-seated passion for technology