Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App

Weather Application using ReactJS

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will develop an Interactive Weather Application using ReactJS Framework. The developed application will provide real-time weather information to the user for the city they have searched. If the user searches, for the wrong city, an Error message is also displayed to the user, stating that the searched city is not found. We have used OpenWeatherMap API which provides us with access to weather data from around the world. We have fetched the weather information for various locations, including wind speed and more.

You can follow the Weather Forecast Project to create your own weather application using HTML, CSS and JavaScript.

Let's have an interactive look at what our final project will look like:

gfg

Technologies Used/Pre-requisites:

  • ReactJS
  • CSS
  • JSX
  • Function Components in React

Approach:

The developed code displays the interactive Weather Application using ReactJS Framework. The application allows users to get information on various cities in real time. With the help of API, we are fetching the weather details of the city which is been searched by the user. The application is completely responsive and the response in terms of the output is also given in a quick time. Navigation to the app components is also easy for the user. The UI is completely user-friendly so that users can easily handle the application. We have used various icons, that made our developed application more attractive.

Project Structure:

PS

The dependencies in package.json will look like this:

"dependencies": {
"@fortawesome/free-solid-svg-icons": "^6.4.2",
"@fortawesome/react-fontawesome": "^0.2.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-loader-spinner": "^5.3.4",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Steps to create the application:

Step 1: Set up React project using the below command in VSCode IDE.

npx create-react-app <<name of project>>

Step 2: Navigate to the newly created project folder by executing the below command.

cd <<Name_of_project>>

Step 3: As we are using various packages for the project, we need to install them. Use the below command to install all the packages that are specified in package.json file.

npm install axios react-loader-spinner @fortawesome/react-fontawesome @fortawesome/free-solid-svg-icons

Example: Insert the below code in the respective files.

  • App.js: All the logic that is been used in the application is programmatically coded in this file. From this file, all the buttons, cards, and icons are been rendered in the web browser.
  • App.css: This file consists of all the styling code, whether it is h1 tag styling or background styling. All the look and feel of the application are specified in this styling file.
JavaScript
//App.js  import { Oval } from 'react-loader-spinner'; import React, { useState } from 'react'; import axios from 'axios'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faFrown } from '@fortawesome/free-solid-svg-icons'; import './App.css';  function GfGWeatherApp() {     const [input, setInput] = useState('');     const [weather, setWeather] = useState({         loading: false,         data: {},         error: false,     });      const toDateFunction = () => {         const months = [             'January',             'February',             'March',             'April',             'May',             'June',             'July',             'August',             'September',             'October',             'November',             'December',         ];         const WeekDays = [             'Sunday',             'Monday',             'Tuesday',             'Wednesday',             'Thursday',             'Friday',             'Saturday',         ];         const currentDate = new Date();         const date = `${WeekDays[currentDate.getDay()]} ${currentDate.getDate()} ${months[currentDate.getMonth()]             }`;         return date;     };      const search = async (event) => {         if (event.key === 'Enter') {             event.preventDefault();             setInput('');             setWeather({ ...weather, loading: true });             const url = 'https://api.openweathermap.org/data/2.5/weather';             const api_key = 'f00c38e0279b7bc85480c3fe775d518c';             await axios                 .get(url, {                     params: {                         q: input,                         units: 'metric',                         appid: api_key,                     },                 })                 .then((res) => {                     console.log('res', res);                     setWeather({ data: res.data, loading: false, error: false });                 })                 .catch((error) => {                     setWeather({ ...weather, data: {}, error: true });                     setInput('');                     console.log('error', error);                 });         }     };      return (         <div className="App">             <h1 className="app-name">                 GeeksforGeeks Weather App             </h1>             <div className="search-bar">                 <input                     type="text"                     className="city-search"                     placeholder="Enter City Name.."                     name="query"                     value={input}                     onChange={(event) => setInput(event.target.value)}                     onKeyPress={search}                 />             </div>             {weather.loading && (                 <>                     <br />                     <br />                     <Oval type="Oval" color="black" height={100} width={100} />                 </>             )}             {weather.error && (                 <>                     <br />                     <br />                     <span className="error-message">                         <FontAwesomeIcon icon={faFrown} />                         <span style={{ fontSize: '20px' }}>City not found</span>                     </span>                 </>             )}             {weather && weather.data && weather.data.main && (                 <div>                     <div className="city-name">                         <h2>                             {weather.data.name}, <span>{weather.data.sys.country}</span>                         </h2>                     </div>                     <div className="date">                         <span>{toDateFunction()}</span>                     </div>                     <div className="icon-temp">                         <img                             className=""                             src={`https://openweathermap.org/img/wn/${weather.data.weather[0].icon}@2x.png`}                             alt={weather.data.weather[0].description}                         />                         {Math.round(weather.data.main.temp)}                         <sup className="deg">°C</sup>                     </div>                     <div className="des-wind">                         <p>{weather.data.weather[0].description.toUpperCase()}</p>                         <p>Wind Speed: {weather.data.wind.speed}m/s</p>                     </div>                 </div>             )}         </div>     ); }  export default GfGWeatherApp; 
CSS
/* App.css */ * {     font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,         Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; }  html {     background-color: #f7f7f7; }  .app-name {     font-size: 2.3rem;     color: rgb(17, 144, 0);     margin-bottom: 16px; }  .App {     display: flex;     flex-direction: column;     justify-content: center;     align-items: center;     width: 600px;     min-height: 440px;     background-color: rgb(255, 255, 255);     text-align: center;     margin: 128px auto;     border-radius: 10px;     padding-bottom: 32px;     box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); }  .city-search {     width: 100%;     max-width: 400px;     box-sizing: border-box;     border: 2px solid rgb(204, 204, 204);     outline: none;     border-radius: 20px;     font-size: 16px;     background-color: #e5eef0;     background-position: 10px 12px;     background-repeat: no-repeat;     padding: 12px 40px 12px 40px;     -webkit-transition: width 0.4s ease-in-out;     transition: width 0.4s ease-in-out;     color: #333; }  .city-search:focus {     width: 100%; }  .city-name {     font-size: 1.5rem;     color: #444;     margin-bottom: 8px; }  .date {     font-size: 1.25em;     font-weight: 500;     color: #777; }  .icon-temp {     font-size: 3rem;     font-weight: 700;     color: #1e2432;     text-align: center; }  .deg {     font-size: 1.3rem;     vertical-align: super; }  .des-wind {     font-weight: 500;     color: #666; }  .error-message {     display: block;     text-align: center;     color: #d32f2f;     font-size: 24px;     margin-top: auto; }  .Loader {     display: flex;     justify-content: center;     align-items: center;     height: 100%; }  .Loader>div {     margin: 0 auto; }  .weather-icon {     display: flex;     justify-content: center;     align-items: center; }  .weather-icon img {     width: 100px;     height: 100px;     border-radius: 50%;     box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); } 

Step 5: Add the other config files like index.js.

Steps to run the application:

1. Execute the following command in the terminal.

npm start

2. Open the web browser and type the following URL in the address bar.

http://localhost:3000/

Output:

gfg


G

gpancomputer
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • ReactJS-Projects

Similar Reads

    BMI Calculator Using React
    In this article, we will create a BMI Calculator application using the ReactJS framework. A BMI calculator determines the relationship between a person's height and weight. It provides a numerical value that categorizes the individual as underweight, normal weight, overweight, or obese.Output Previe
    3 min read
    Create Rock Paper Scissor Game using ReactJS
    In this article, we will create Rock, Paper, Scissors game using ReactJS. This project basically implements class components and manages the state accordingly. The player uses a particular option from Rock, Paper, or Scissors and then Computer chooses an option randomly. The logic of scoring and win
    6 min read
    Create a Form using React JS
    Creating a From in React includes the use of JSX elements to build interactive interfaces for user inputs. We will be using HTML elements to create different input fields and functional component with useState to manage states and handle inputs. Prerequisites:Functional ComponentsJavaScript ES6JSXPr
    5 min read
    Create a Random Joke using React app through API
    In this tutorial, we'll make a website that fetches data (joke) from an external API and displays it on the screen. We'll be using React completely to base this website. Each time we reload the page and click the button, a new joke fetched and rendered on the screen by React. As we are using React f
    3 min read
    Nutrition Meter - Calories Tracker App using React
    GeeksforGeeks Nutrition Meter application allows users to input the name of a food item or dish they have consumed, along with details on proteins, calories, fat, carbs, etc. Users can then keep track of their calorie intake and receive a warning message if their calorie limit is exceeded. The logic
    9 min read
    Currency converter app using ReactJS
    In this article, we will be building a very simple currency converter app with the help of an API. Our app contains three sections, one for taking the user input and storing it inside a state variable, a menu where users can change the units of conversion, and finally, a display section where we dis
    4 min read
    Lap Memory Stopwatch using React
    Stopwatch is an application which helps to track time in hours, minutes, seconds, and milliseconds. This application implements all the basic operations of a stopwatch such as start, pause and reset button. It has an additional feature using which we can keep a record of laps which is useful when we
    5 min read
    Typing Speed Tester using React
    In this article, we will create a Typing Speed Tester that provides a random paragraph for the user to type as accurately and quickly as possible within a fixed time limit of one minute. This application also displays the time remaining, counts mistakes calculates the words per minute and characters
    9 min read
    Number Format Converter using React
    In this article, we will create Number Format Converter, that provides various features for users like to conversion between decimal, binary, octal and hexadecimal representations. Using functional components and state management, this program enables users to input a number and perform a range of c
    7 min read
    Create a Password Validator using ReactJS
    Password must be strong so that hackers can not hack them easily. The following example shows how to check the password strength of the user input password in ReactJS. We will use the validator module to achieve this functionality. We will call the isStrongPassword function and pass the conditions a
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences