NM Main Report Harish PDF
NM Main Report Harish PDF
INTRODUCTION
The Weather API React Web Application project aims to provide a user-
friendly platform that delivers accurate and real-time weather information. Using
React, a powerful front-end JavaScript library, this application interacts with
public weather APIs to fetch and display weather data for different locations. This
project is designed to be scalable, responsive, and feature-rich, offering users an
intuitive interface to explore weather conditions effortlessly.
1
meteorological data like temperature, humidity, wind speed, and precipitation
forecasts. With advancements in technology, they have become accessible to
global audiences through web and mobile platforms.
Weather apps leverage APIs to access real-time and historical weather data.
They cater to various use cases, such as helping individuals plan their travel,
aiding farmers with crop decisions, or informing businesses of weather-
dependent activities. This project aims to create such an application, highlighting
React’s strengths in building interactive user interfaces and robust data handling.
Real-time Weather Updates: Users can instantly retrieve the current weather
conditions for any specified location.
Forecast Information: The app provides predictions for upcoming days, aiding
long-term planning.
Global Accessibility: Users can input any city worldwide and access weather
data, ensuring a versatile user experience.
Visual Elements: Data like temperature trends and weather conditions are
displayed with icons and charts for better understanding.
Use Cases:
Travel Planning: Travelers can plan their trips by checking weather forecasts for
their destinations.
2
Event Management: Organizers can choose dates and venues based on predicted
weather conditions.
Outdoor Activities: Enthusiasts can plan activities like hiking or sports events
with real-time updates.
3
CHAPTER 2
4. Verify installation:
node -v
npm -v
These commands confirm that Node.js and npm are correctly installed.
4
2.2 Setting Up React Project with Create-React-App
cd weather-app
npm start
5
React Router: Enables routing within the application, allowing navigation
between different views.
6
CHAPTER 3
Key Benefits:
Support for global locations and advanced features like air quality metrics.
This project utilizes a weather API to fetch data like temperature, humidity, wind
speed, and forecasts. Developers must understand API endpoints, request
parameters, and response formats to ensure seamless integration.
API keys authenticate requests, ensuring secure and controlled access to services.
Steps to obtain an API key:
https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_A
PI_KEY
7
API providers often set usage limits, so developers must optimize API calls to
avoid exceeding quotas.
Air Quality Index (Optional): Gives data on pollutants and air quality.
Responses are generally in JSON format, containing fields like temp, humidity,
and weather. Parsing this data is crucial for presenting it effectively in the
application.
8
CHAPTER 4
Advantages:
Components should receive props for flexibility and avoid hardcoding data.
9
2. Define routes in App.js:
<Router>
<Routes>
</Routes>
</Router>
10
CHAPTER 5
3. Making API Requests: Use the axios.get method to fetch data from the
weather API:
console.log(response.data);
} catch (error) {
11
4. Handling Asynchronous Responses: Use async/await or .then() for handling
asynchronous calls effectively.
Axios enables seamless communication with the weather API, ensuring efficient
data retrieval for the application.
Handling errors and edge cases is crucial for providing a robust user
experience. APIs may fail due to network issues, incorrect API keys, or exceeding
usage limits.
Invalid API Key: Ensure the API key is valid and properly included in the
request.
Rate Limits: Implement mechanisms to monitor API usage and avoid exceeding
limits.
12
Error Handling Techniques:
try {
} catch (error) {
console.error('Error:', error);
API responses are usually in JSON format, requiring data extraction and
transformation for display in the UI.
Inspect the API Response: Analyze the structure using browser developer tools
or console.log(response.data).
13
Convert temperature from Kelvin to Celsius:
Pass Data to Components: Use props to pass parsed data to UI components for
rendering:
Parsing ensures that raw API data is translated into user-friendly information,
enhancing the application's usability.
14
CHAPTER 6
The search bar is a critical feature, allowing users to input city names and
fetch weather data. This reusable component enhances interactivity and usability.
if (query) onSearch(query);
};
return (
<div>
<input
type="text"
value={query}
<button onClick={handleSearch}>Search</button>
</div>
15
);};
Event Handling: Capture input changes and trigger the onSearch function when
the button is clicked.
return (
<div>
<h2>Current Weather</h2>
<p>Humidity: {humidity}%</p>
<p>Condition: {description}</p>
</div>
);
};
16
Pass Data via Props: Ensure the component receives parsed weather data.
Styling: Use CSS or Material-UI to format the layout and add icons for visual
appeal.
Styling transforms the application's UI, improving user experience and visual
appeal.
Styling Techniques:
/* WeatherCard.module.css */
.card {
background: #f0f8ff;
padding: 20px;
border-radius: 8px;
<Card>
<CardContent>
17
<Typography>{description}</Typography>
</CardContent>
</Card>
);
Styling ensures the application is not only functional but also aesthetically
pleasing and accessible across devices.
18
CHAPTER 7
navigator.geolocation.getCurrentPosition(position) =>
console.log(latitude, longitude);
},
(error) => {
});
Fetching Weather Data: Pass the latitude and longitude to the weather API:
try {
19
api.openweathermap.org/data/2.5/weather?lat=
${lat}&lon=${lon}&appid=YOUR_API_KEY`);
console.log(response.data);
} catch (error) {
Enhancing UX: Display a loading spinner while fetching location and weather
data.
try {
20
console.log(response.data);
} catch (error) {
};
Parse and Group Data: Extract data points for specific times (e.g., 12 PM
daily):
Design Forecast Cards: Create reusable components to display the forecast for
each day:
<div>
<h4>{date}</h4>
<p>{temp} °C</p>
<p>{description}</p>
</div>);
Integrate into UI: Map the forecast data into ForecastCard components and
display them in a grid.
Styling: Use CSS/Material-UI to format and add icons for weather conditions.
Multi-day forecasts provide users with actionable insights for planning their
activities.
21
7.3 Adding Graphs/Charts for Weather Trends
const chartData = {
datasets: [
borderColor: 'blue',
fill: false,
},
],
};
};
22
export default TemperatureChart;
time: item.dt_txt,
}));
23
CHAPTER 8
STATE MANAGEMENT
Example:
useEffect(() => {
fetchWeather();
}, []);
24
import { createStore } from 'redux';
Save data:
localStorage.setItem('recentSearch', JSON.stringify(data));
Retrieve data:
25
CHAPTER 9
Implementation:
React Implementation:
Use a conditional rendering method to show the loading indicator while data is
being fetched or processed.
Best Practices:
Allow users to continue interacting with other parts of the app if possible while
data is loading.
Customize loading indicators to match the app’s theme and design style.
Implementation:
26
UI Approach: Display a user-friendly error message when the API call fails.
This could be a simple text message or an alert box depending on the severity of
the issue.
React Implementation:
Best Practices:
Ensure that error messages are clear and actionable (e.g., "Please check your
internet connection").
Objective: Ensuring the app is usable on various devices and screen sizes,
providing a consistent experience for users across mobile, tablet, and desktop.
Implementation:
Responsive Design Principles: Use flexible layouts, media queries, and relative
units (percentages, em, rem) to ensure that the app scales across different screen
sizes.
React Implementation:
27
Best Practices:
28
CHAPTER 10
Optimize Assets: Minimize and bundle CSS and JavaScript files to reduce load
times.
Error Handling: Ensure all errors are handled properly to avoid crashes in
production.
Build Process: Run npm run build or equivalent to generate the production
build.
Best Practices:
29
Steps for Deployment:
Vercel:
Vercel automatically builds and deploys the app with every push to the
connected branch.
Netlify:
Best Practices:
30
APPENDIX
SOURCE CODE
2) src (Folder)
1. assets (Folder)
a) cloudy-weather.png
b) drizzle.png
c) humidity.png
d) rain.png
e) search.png
f) snow.png
g) sun
h) weather-app.png
i)weatherhome.png
j)wind.png
3) app.css
4) app.js
5) main.jsx
6) index.html
7) package-lock.json
31
8) package.json
1) app.css
*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: sans-serif;
.main {
background-size: cover;
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
.container {
width: 350px;
background-color: white;
32
height: auto;
border-radius: 10px;
padding: 10px;
.search {
height: auto;
padding: 10px;
display: flex;
justify-content: center;
border-radius: 5px;
width: 90%;
.search input {
width: 95%;
border: none;
background-color: white;
outline: none;
.img-search {
33
height: 20px;
width: 20px;
cursor: pointer;
.image {
text-align: center;
height: 100px;
.image img {
height: 80px;
width: 80px;
.temper,.city,.country {
font-size: 35px;
text-align: center;
margin-top: 10px;
text-transform: uppercase;
.temper {
font-size: 25px;
font-weight: bold;
34
}
.city {
color: orange;
.country {
font-size: 15px;
color: #888;
font-weight: 500;
.cord {
display: flex;
justify-content: center;
gap: 30px;
margin-top: 20px;
padding: 10px;
.cord div {
display: flex;
flex-direction: column;
gap: 5px;
align-items: center;
35
.cord2 {
display: flex;
justify-content: space-between;
margin-top: 10px;
padding: 20px;
.cord2 div {
display: flex;
flex-direction: column;
gap: 5px;
align-items: center;
.humidity-icon{
height: 25px;
width: 25px;
.wind-icon{
height: 25px;
width: 50px;
.designed{
text-align: center;
36
font-size: 10px;
.designed span{
color: orangered;
font-size: 10px;
font-style: italic;
font-weight: bold;
.loading{
text-align: center;
margin: 15px;
.citynot{
text-align: center;
font-family: cursive;
font-weight: bolder;
font-size: 30px;
margin: 15px;
background-color: red;
padding: 10px;
border-radius: 5px;
37
color: white;
2)app.jsx
import './App.css'
return (
<div>
<div className='image'>
</div>
<div className="temper">{temp}°C</div>
38
<div className="city">{city}</div>
<div className="country">{country}</div>
<div className="cord">
<div>
<span className='lat'>Latitude</span>
<span>{lat}</span>
</div>
<div>
<span className='log'>Longitude</span>
<span>{log}</span>
</div>
</div>
<div className="cord2">
<div>
<span>{humidity}%</span>
<span>Humidity</span>
</div>
<div>
<span>{windspeed} km/h</span>
<span>Wind Speed</span>
39
</div>
</div>
</div>
const weatherIconMap = {
"01d" : SunIcon,
"01n" : SunIcon,
40
"02d" : CloudWeatherIcon,
"02n" : CloudWeatherIcon,
"03d" : DrizzleIcon,
"03n" : DrizzleIcon,
"04d" : DrizzleIcon,
"04n" : DrizzleIcon,
"09d" : RainIcon,
"09n" : RainIcon,
"010d" : RainIcon,
"010n" : RainIcon,
"013d" : SnowIcon,
"013n" : SnowIcon,
setLoading(true);
let url =
`https://api.openweathermap.org/data/2.5/weather?q=${text}&appid=${api_key
}&units=Metric`;
try {
41
console.log("City not found ra thambi");
setCityNotFound(true);
setLoading(false);
setLat(data.coord.lat);
setLog(data.coord.lon);
setCity(data.name);
setHumidity(data.main.humidity);
setWindspeed(data.wind.speed);
setTemp(Math.floor(data.main.temp));
setCountry(data.sys.country)
setIcon(weatherIconMap[weatherIcon] || SunIcon);
setCityNotFound(false);
} catch (error) {
} finally {
setLoading(false);
setText(e.target.value);
42
}
search();
useEffect(function () {
search();
},[]);
return (
<div className='main'>
<div className='container'>
<div className='search'>
</div>
43
{/* <p className='designed'>Designed by <span>KATHIRESAN</span></p>
*/}
</div>
</div>
3)main.jsx
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
4)index.html
<!doctype html>
<html lang="en">
<head>
44
<title>Web Application</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
5)package.json
"name": "mk-weather-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
45
},
"devDependencies": {
"@types/react": "^18.2.56",
"@types/react-dom": "^18.2.19",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.56.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"vite": "^5.1.4"
46
APPENDIX
SCREENSHOTS
OUTPUT:
47
Search City
48
REFERENCE
API’s:
ONLINE RESOURCES:
RESEARCH PAPERS:
49
CONCLUSION
The Current Weather Checking API is a robust and reliable solution for
developers seeking to integrate accurate and real-time weather data into their
applications. By providing instant access to current weather conditions, forecasts,
and weather alerts, this API enables developers to build innovative and user-
centric applications that cater to various industries, including weather forecasting,
travel, tourism, smart home automation, and more. The API's ability to deliver
precise and up-to-date weather information empowers developers to enhance user
experiences, improve decision-making, and drive business growth. Furthermore,
the Current Weather Checking API's scalability, flexibility, and ease of integration
make it an ideal choice for developers seeking to create cutting-edge applications
that meet the evolving needs of their users.
50