"I'm learning React, but I don't know how to use the API..."
Such a beginner's problem,Build a weather forecast appLet's solve this neatly.
In this article,How to use the OpenWeatherMap API with React to get real-time weatherWe will explain the above in an easy-to-understand and detailed manner.
How to make a weather forecast app using React
Conclusion: Perfect for your first step in API integration
By creating a weather forecast app with React,How to use APIs, state management, asynchronous communication (fetch)You will learn the basics all at once.
Tools and preparation
What you need:
- Node.js (https://nodejs.org/ja)
- OpenWeatherMap API key (https://openweathermap.org/api)
- create-react-app
Project creation command:
1 | npx create-react-app react-weather-app cd react-weather-app npm start |
How to obtain and set an API key
Registering the OpenWeatherMap API
You can get an API key with a free plan from the official website.
After acquisition,.env
Put the following in the file:
1 | REACT_APP_WEATHER_API_KEY=xxxxxx |
Implementation to get weather data
Basic configuration of App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import React, { useState } from "react"; function App() { const [city, setCity] = useState(""); const [weather, setWeather] = useState( null ); const fetchWeather = async () => { if (!city) return ; const response = await fetch( `https: //api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.REACT_APP_WEATHER_API_KEY}&units=metric&lang=ja` ); const data = await response.json(); setWeather(data); }; return ( <div style= "{{" textalign: "center" }}> <h1>Weather forecast app</h1> <input type= "text" value= "{city}" onchange= "{(e)" > setCity(e.target.value)} placeholder="Enter city name" /> <button onclick= "{fetchWeather}" >search</button> {weather && weather.main && ( <div> <h2>{weather.name}</h2> <p>Temperature: {weather.main.temp}℃</p> <p>Weather: {weather.weather[0].description}</p> </div> )} </div> ); } export default App; |
Common errors and solutions
"City not found" is displayed
- Input error (It is recommended to input in English, not in Japanese)
- API Key Restrictions
API key is not reflected
.env
After changingnpm start
Let's restart.
Reference links from public institutions
- Guidelines for using Japan Meteorological Agency data: https://www.jma.go.jp/jma/kishou/info/coment.html
- GIGA School Initiative (Ministry of Education, Culture, Sports, Science and Technology): https://www.mext.go.jp/a_menu/other/index_00001.htm
Completed code summary
Once you write all the code in App.js, the weather forecast app will be complete.
Just replace the API key with your own.
Summary: Learn API basics through practice
A weather app can be a great first step in integrating React with an API.
"API call → Status management → Display"This flow will come naturally to you.
In the next step, let's try expanding it to display maps and weekly weather forecasts.