Hey developers hope you are fine, let’s look at how to build a weather app in React JS from scratch, by building a weather app we will use Weather API to get the live weather details. So, we are using OpenWeather API to get data. You can get a lot of data from API, you can add any data as you want.
Weather functions are common for offering real-time climate info. Constructing one in React JS is an effective way to be taught and follow frontend growth expertise. This text will inform you about the important ideas and parts wanted to create an easy climate app without delving into the precise code.
React JS is a JavaScript library used to construct consumer interfaces. It helps builders create interactive UIs with reusable parts. These parts enable environment-friendly updates and rendering, making React a superb selection for a climate app that should show dynamic climate knowledge.
How to Build Weather App in React JS
Before moving on to codes, you should watch the tutorial that will help you practically understand everything from scratch. I hope the video is more helpful than codes.
I hope you’ve watched completed video and you’ve learned something new from this tutorial. let’s see the codes that are used to build a weather app in react js.
You May Also Like:
- How to Make a Quiz App in React JS
- How to Make Form Validation in React JS
- Create a Multi-Step Form in React JS
- How to Create Todo App in React JS
The design of a climate app ought to be clear and intuitive, and include parts similar to a search bar, climate icons, temperature readings, and probably further particulars like humidity and wind velocity. Climate knowledge could be obtained from APIs like OpenWeatherMap. The app must fetch knowledge from the API based mostly on the consumer’s location or search question and show it.
First of All, you need to make a vite project in React JS and then you can cleanup the App file, just use the WeatherApp component inside the file. Once you did that
import React from "react";
import WeatherApp from "./component/WeatherApp";
function App() {
return <WeatherApp />;
}
export default App;
Then the next thing you need to work with WeatherApp components to get the data from API and display it on your application. Here is Weather App component codes.
import React, { useEffect, useState } from "react";
import WeatherLeftContent from "./WeatherLeftContent";
const API_KEY = "8adce966beac5b681395c0e7904c4b40";
function WeatherApp() {
const [country, setCountry] = useState({});
const [inputEl, setInput] = useState();
const [isError, setError] = useState(false);
async function Weather() {
try {
const data = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${inputEl}&appid=${API_KEY}`,
);
const result = await data.json();
setCountry(result);
} catch (error) {
console.log(error);
}
}
function handleForm(e) {
e.preventDefault();
if (inputEl !== "") {
setInput(inputEl);
Weather();
console.log(inputEl, country);
}
setInput("");
}
useEffect(
function () {
if (country.cod === "404") {
setError(true);
}
return () => {
setError(false);
};
},
[handleForm],
);
return (
<div className="weather-container">
<div className="weather--wrapper">
<div className="weather--img">
<WeatherLeftContent handelCountry={country} />
</div>
<div className="weather_content">
<form onSubmit={handleForm}>
<input
type="text"
placeholder="Search Location"
onChange={(e) => setInput(e.target.value)}
value={inputEl}
/>
<button className="btn_search">Search</button>
</form>
<div className="day_info">
<div className="content">
<p className="title">NAME</p>
<span className="value">{country.name}</span>
</div>
<div className="content">
<p className="title">TEMP</p>
<span className="value">
{country.main
? Math.round(country.main.temp - 275.15) + "°C"
: ""}
</span>
</div>
<div className="content">
<p className="title">HUMIDITY</p>
<span className="value">
{country.main ? country.main.humidity + "%" : ""}
</span>
</div>
<div className="content">
<p className="title">WIND SPEED</p>
<span className="value">
{country.main ? country.wind.speed + "km/h" : ""}
</span>
</div>
</div>
{isError && <div>Please Enter Valid Country Name</div>}
</div>
</div>
</div>
);
}
export default WeatherApp;
Then you need to design another component namely the WeatherLeftContent component inside the file you need to display the API data such as Temp, description, pic etc.
import React from "react";
import { Days } from "../days";
// display day
const day = new Date();
const dayName = Days[day.getDay()];
// display Date
let month = day.toLocaleString("default", { month: "long" });
let date = day.getDate();
let year = day.getFullYear();
function WeatherLeftContent({ handelCountry }) {
return (
<div className="default_info">
<h2 className="default_day">{dayName}</h2>
<span className="default_date">{`${date} ${month} ${year}`}</span>
<div className="icons">
{handelCountry.main ? (
<img
src={`https://openweathermap.org/img/wn/${handelCountry.weather[0].icon}@4x.png`}
alt=""
/>
) : (
<img src="https://openweathermap.org/img/wn/[email protected]" alt="" />
)}
<h2>
{handelCountry.main
? Math.round(handelCountry.main.temp - 275.15) + "°C"
: 25 + "°C"}
</h2>
<h3 className="cloudtxt">
{handelCountry.main
? handelCountry.weather[0].description
: "Overcast Clouds"}
</h3>
</div>
</div>
);
}
export default WeatherLeftContent;
That’s for the weather App in react js, but the last thing you need to add styling to design the application, let me share with you the CSS codes that are help you to design the Application.
@import url("https://fonts.googleapis.com/css2?family=Jost:ital,wght@0,100..900;1,100..900&display=swap");
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
font-family: "jost", sans-serif;
height: 100vh;
}
.weather-container {
width: 900px;
background-color: #232931;
color: #fff;
border-radius: 25px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.35);
}
.weather--wrapper {
display: grid;
grid-template-columns: 3fr 4fr;
grid-gap: 1rem;
}
.weather--img {
border-radius: 25px;
background-image: url("./assets/bg.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
transform: scale(1.05) perspective(300px);
position: relative;
}
.weather--img::before {
content: "";
position: absolute;
width: 100%;
height: 100%;
background: linear-gradient(135deg, #5c6bc0 10%, #0d47a1 100%);
opacity: 0.5;
z-index: -1;
border-radius: 25px;
}
.default_info {
padding: 1.5rem;
text-align: center;
}
.default_info img {
width: 80%;
object-fit: cover;
margin: 0 auto;
}
.default_info h2 {
font-size: 3rem;
}
.default_info h3 {
font-size: 1.3rem;
text-transform: uppercase;
}
.weather_temp {
font-size: 4rem;
font-weight: 800;
}
/* ========Content */
.weather_content {
padding: 1.5rem;
}
.weather_content form {
margin: 1.5rem 0;
position: relative;
}
.weather_content form input {
width: 100%;
outline: none;
border: 1px solid #37474f;
border-radius: 5px;
padding: 0.7rem 1rem;
font-family: inherit;
font-size: 1rem;
background-color: transparent;
color: #fff;
}
.weather_content form button {
position: absolute;
top: 0;
right: 0;
border-top-right-radius: 5px;
border-top-right-radius: 5px;
padding: 0.85rem 0.7rem;
font-family: inherit;
font-size: 0.8rem;
outline: none;
cursor: pointer;
background-color: #5c6bc0;
border: none;
color: #fff;
}
.day_info {
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 0.4rem 0;
}
.day_info .content {
display: flex;
justify-content: space-between;
margin: 1rem 0;
}
.day_info .content .title {
font-weight: 600;
}
State in React holds knowledge that may change over time, similar to climate information. Correct state administration ensures the app updates the UI accurately every time new knowledge is fetched. A React climate app sometimes contains several parts: a search bar for consumer entries, a show space for climate knowledge, and probably a forecast part for the upcoming climate. Breaking the app into these parts helps organize code and ensures reusability.
The app ought to be responsive, which means it appears to be good on each desktop and cell unit. That is essential as a result of customers might enter the app on numerous units. To start out, arrange React surroundings utilizing instruments like Create React App, which offers a fast setup with smart defaults.
Subsequently, construct particular person parts for every part of the app, similar to Search and WeatherDisplay, every specializing in a selected piece of performance. Join the app to a climate API utilizing JavaScript’s Fetch API or the Axios library to make HTTP requests. Deal with the responses to extract related climate knowledge. Use React’s useState hook to handle the knowledge that modifications, such as the climate info, make certain the UI updates every time the state modifications.
Type the app utilizing CSS or libraries like styled components, specializing in making the UI intuitive and visually interesting.
Last Touches and Deployment
After constructing the app, thorough testing is essential to make sure all functionalities work as anticipated. As soon as happy, deploy the app utilizing companies like GitHub Pages, Netlify, or Vercel to make it accessible to customers worldwide.
Conclusion
Constructing a climate app in React JS is a sensible mission that helps builders perceive the core ideas of React and frontend growth. It entails making a user-friendly interface, managing state, and integrating exterior APIs. This mission not solely teaches technical expertise but additionally offers a useful gizmo for on a regular basis use.