Create a weather Application using React Redux
Last Updated :
30 Apr, 2024
Weather App is a web application designed to provide real-time weather information for any location worldwide. In this article, we will make a Weather App using React and Redux. It offers a seamless and intuitive user experience, allowing users to easily access accurate weather forecasts ( temperature, wind speed, humidity etc.) by just entering any city name.
Project preview:
Weather AppPrerequisites:
Approach
- React App & dependencies : Use Create React App to set up a new React project named weather-app and install Redux, React Redux and Axios.
- Redux Setup : Create a store.js file to set up the Redux store, define required reducers and actions and use createStore method to create store.
- Weather API : Select a weather API platform, create an account, and integrate its keys and endpoint into your React app.
- Component : Implement weather display, location input, loading indicator, and error message in the weather app and also integrating Redux state and actions.
Steps to Create React Application
Step 1: Create React Application named weather-app and navigate to it using this command.
npx create-react-app weather-app
cd weather-app
Step 2: Install required packages and dependencies.
npm install react-redux redux axios
Updated dependencies in package.json file
Installed dependencies will look like the below file in package.json file.
"dependencies": {
"axios": "^1.6.8",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.1",
"redux": "^5.0.1"
},
File structure:
Project Structure
Example:
CSS
/* App.css */
#App-wrapper {
/* text-align: center; */
justify-content: center;
display: flex;
}
#app {
text-align: center;
width: 500px;
display: flex;
flex-direction: column;
}
#head {
display: flex;
gap: 10px;
align-items: center;
}
input {
padding: 10px 20px;
border: 1px solid black;
margin: 5px;
}
button {
padding: 10px 20px;
border: 1px solid black;
/* margin: 5px; */
cursor: pointer;
background-color: rgb(230, 230, 230);
}
button:hover {
background-color: rgba(9, 204, 9, 0.61);
}
p {
background-color: rgb(230, 230, 230);
padding: 10px 20px;
margin: 5px 0px;
text-transform: capitalize;
}
p span {
color: green;
}
JavaScript
// store.js
import { createStore, combineReducers } from "redux";
// actions
export const fetchWeatherRequest = () => ({
type: "FETCH_WEATHER_REQUEST",
});
export const fetchWeatherSuccess = (data) => ({
type: "FETCH_WEATHER_SUCCESS",
payload: data,
});
export const fetchWeatherFailure = (error) => ({
type: "FETCH_WEATHER_FAILURE",
payload: error,
});
// reducers/weatherReducer.js
const initialState = {
weatherData: null,
loading: false,
error: null,
};
const weatherReducer = (state = initialState, action) => {
switch (action.type) {
case "FETCH_WEATHER_REQUEST":
return {
...state,
loading: true,
error: null,
};
case "FETCH_WEATHER_SUCCESS":
return {
...state,
loading: false,
weatherData: action.payload,
};
case "FETCH_WEATHER_FAILURE":
return {
...state,
loading: false,
error: action.payload,
};
default:
return state;
}
};
// store.js
const rootReducer = combineReducers({
weather: weatherReducer,
// Add more reducers if needed
});
const store = createStore(rootReducer);
export default store;
JavaScript
// App.js
import React, { useState } from "react";
import axios from "axios";
import { connect } from "react-redux";
import {
fetchWeatherRequest,
fetchWeatherSuccess,
fetchWeatherFailure,
} from "./store";
import "./App.css";
const WeatherApp = ({ weatherData, loading, error, fetchWeather }) => {
const [city, setCity] = useState("");
const findHandle = async () => {
await fetchWeather(city);
};
console.log(weatherData);
return (
<div id="App-wrapper">
<div id="app">
<div id="head">
<img
src="https://media.geeksforgeeks.org/gfg-gg-logo.svg"
alt="gfg_logo"
/>
<label>Enter City Name</label>
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
/>
<button onClick={findHandle}>Find</button>
</div>
<div>
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
{weatherData && (
<div>
<div>
<img src={weatherData?.current?.condition.icon} />
<p>{weatherData?.current?.condition.text}</p>
</div>
<div>
<p>
Temperature : <span>{weatherData?.current?.temp_c}c</span>
</p>
<p>
Humidity : <span>{weatherData?.current?.humidity}</span>
</p>
<p>
Wind Speed : <span>{weatherData?.current.wind_kph}kph</span>
</p>
</div>
<div>
{Object.keys(weatherData?.location).map((key) => (
<p key={key}>
{key} : <span>{weatherData.location[key]}</span>
</p>
))}
</div>
</div>
)}
</div>
</div>
</div>
);
};
const mapStateToProps = (state) => ({
weatherData: state.weather.weatherData,
loading: state.weather.loading,
error: state.weather.error,
});
const mapDispatchToProps = (dispatch) => ({
fetchWeather: (city) => {
dispatch(fetchWeatherRequest());
fetchWeatherData(city)
.then((data) => dispatch(fetchWeatherSuccess(data)))
.catch((err) => dispatch(fetchWeatherFailure(err.message)));
},
});
// feathermatch function
async function fetchWeatherData(city = "Delhi") {
const API_KEY = "XXXXX-XXXXX-XXXXX";
const response = await axios.get(
`https://api.weatherapi.com/v1/current.json?q=${city}&key=${API_KEY}`
);
console.log(response);
if (response.status != 200) {
throw new Error("Failed to fetch weather data");
}
return response.data;
}
export default connect(mapStateToProps, mapDispatchToProps)(WeatherApp);
JavaScript
// index.js
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<App />
</Provider>
);
Command to Run Weather Application:
To run weather application open your terminal and navigate to weather-app directory and enter the following command.
npm start
Output:
Weather App
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read