BeginnerCoder
intermediate#react#weather app#api

Building a Simple Weather App with React

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to create a simple weather application using React, including fetching data from an API and displaying the current weather.

Introduction to Weather App

In this tutorial, we will build a simple weather application using React. This application will fetch data from an API and display the current weather.

Step 1: Setting Up the Project

First, we need to set up a new React project. We can do this by running the following command in our terminal:

npx create-react-app weather-app

Step 2: Creating the Weather Component

Next, we need to create a new component for our weather application. We can do this by creating a new file called Weather.js in the src directory:

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

function Weather() {
    const [weather, setWeather] = useState({});

useEffect(() => {
        fetch('https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY')
            .then(response => response.json())
            .then(data => setWeather(data));
    }, []);

return (
        <div>
            <h1>Current Weather</h1>
            <p>Temperature: {weather.main && weather.main.temp}°C</p>
            <p>Humidity: {weather.main && weather.main.humidity}%</p>
        </div>
    );
}

export default Weather;

Step 3: Rendering the Weather Component

Finally, we need to render our Weather component in the App.js file:

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

function App() {
    return (
        <div>
            <Weather />
        </div>
    );
}

export default App;
Keep going with react

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.