Creating a Weather App with React JS in 2024: A Step-by-Step Guide to Using Weather API in Your React Project

Posted by


In this tutorial, we will be creating a weather app using React JS and a Weather API. React JS is a popular JavaScript library for building user interfaces, and it is known for its simplicity and reusability. The Weather API we will be using provides current weather information for any city around the world. By the end of this tutorial, you will have a fully functional weather app that displays the current weather conditions of a given city.

Step 1: Set up your environment
Before we begin building our weather app, make sure you have Node.js and npm installed on your computer. If you don’t have these installed already, you can download and install them from the official Node.js website.

To create a new React app, run the following command in your terminal:

npx create-react-app weather-app
cd weather-app

Step 2: Install Axios
We will be using Axios to make API requests in our React app. To install Axios, run the following command in your terminal:

npm install axios

Step 3: Get API key
To use the Weather API, you will need to sign up for an API key. Visit the Weather API website and sign up for a free account to get your API key.

Step 4: Create Weather component
Inside the src folder of your React app, create a new component called Weather.js. This component will fetch weather data from the Weather API and display it on the screen. Add the following code to Weather.js:

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

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

    const getWeather = async () => {
        const response = await axios.get(`http://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${city}`);
        setWeatherData(response.data);
    }

    return (
        <div>
            <input 
                type="text" 
                placeholder="Enter city name"
                value={city}
                onChange={(e) => setCity(e.target.value)}
            />
            <button onClick={getWeather}>Get Weather</button>
            {weatherData && (
                <div>
                    <h2>{weatherData.location.name}</h2>
                    <p>{weatherData.current.condition.text}</p>
                    <p>Temperature: {weatherData.current.temp_c}°C</p>
                    <img src={weatherData.current.condition.icon} alt="weather icon" />
                </div>
            )}
        </div>
    );
}

export default Weather;

Step 5: Import Weather component
In your App.js file, import the Weather component and add it to the render method:

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

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

export default App;

Step 6: Test your app
Now that you have created the Weather component and added it to your App component, run your React app by running the following command in your terminal:

npm start

Once your app is running, open it in your browser and enter a city name into the text input. Click the Get Weather button to make an API call and display the current weather conditions for the given city.

Congratulations! You have successfully created a weather app using React JS and a Weather API. You can further enhance this app by adding more features such as a 5-day forecast, weather charts, or user authentication. Experiment with different API endpoints and React components to create a more robust weather application.

0 0 votes
Article Rating

Leave a Reply

22 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@TaibaSajid-e1m
2 hours ago

how to do it if m not using vite?

@godneo2190
2 hours ago

im getting error of undefined reading 0 how to resolve it can anyone help me

@Rose-gb1ku
2 hours ago

Easy to implement thank you !

@YouTubeMastery101
2 hours ago

thanks sir i complete this time

@kumarc4989
2 hours ago

unable to link api…its shows eroor 401

@phetnikonephandolack3481
2 hours ago

Yo guy ,if you guy lazy to click the serach icon ,add this one on your input :

<div className="search-bar">
<input
ref={inputRef}
type="text"
placeholder="Search"
onKeyDown={(e) => {
if (e.key === "Enter") {
search(inputRef.current.value);
}
}}
/>
<img
src={search_icon}
alt=""
onClick={() => search(inputRef.current.value)}
/>
</div>

thank me later 😎

@paintingitsalifestyle307
2 hours ago

thank you ❤❤

@ezeprince9974
2 hours ago

Nice one. Any idea of building a contour coordinates in python?

@AzeemButt.x
2 hours ago

can you please send the source code there is a isuue of my api linking

@Bscwala1
2 hours ago

caret blink animation how do u do that

@runningmanslowly9072
2 hours ago

source code anyone
pls

@preranaattarde8297
2 hours ago

Excellent Project and API is very fast Working👍👍

@ManieshSanwal
2 hours ago

please let us know your vs code colour theme. I genuinely like this 🤗🤗

@ZeeshanKhan-x6h7j
2 hours ago

how to convert thisproject to antD?

@vaishnavikalkekar3329
2 hours ago

Sir mere me na console ka object nahi dikh raha hai please sir how to solve it

@imemperor6658
2 hours ago

sir here the api key is not working, i properly copy the key which given by wesbite but still saying invalid, please helpout

@pavankumar-of4ew
2 hours ago

problem with API key , it is getting unauthorized while calling city

@cranticumar9888
2 hours ago

sir in react js project, how to access that .env variable. like this not work sir, const wAPI = process.env.whetherApi . in my .env —> (whetherApi = ''adndndddmddmd')
wAPI I assigned in which you assign 'VITE_WHETHER_API'

@hunterhalvorson6223
2 hours ago

PSA, if you have never used openweatherapp, your api may take a couple hours to load

@rayblinks2me
2 hours ago

Thank you very much for your efforts! Project is great for beginners and it shows so much information. From React hooks, to jsx, creating react app using Vite, Fetch, API requests, Google dev tools, async code, try catch code blocks with alerts, ternary's and so much more. Great project!

22
0
Would love your thoughts, please comment.x
()
x