Introduction
A React Weather Application is a practical project for learning how React works with user input, state, APIs, asynchronous JavaScript, loading states, and error handling. In this chapter, you will build weather-related features step by step. You will learn how to take a city name from the user, request weather data from an API, display the result, and handle loading, errors, and invalid searches. React js Weather Application Practice Questions with Solutions to help you understand the concepts of React Weather Applications.
1. Create a Basic Weather Application UI
Problem Statement
Create a simple React weather application that displays a heading, city name, temperature, and weather condition.
React Solution
function WeatherApp() {
return (
<div>
<h1>Weather App</h1>
<h2>Delhi</h2>
<p>Temperature: 32°C</p>
<p>Condition: Sunny</p>
</div>
);
}
export default WeatherApp;
Output
Weather App
Delhi
Temperature: 32°C
Condition: Sunny
Explanation
The WeatherApp component displays basic weather information using JSX. At this stage, the values are static.
Later, these values can come from an API.
Concepts Covered
- React component
- JSX
- Basic UI structure
- Exporting a component
2. Take City Name from the User
Problem Statement
Create a weather application with an input field where the user can enter a city name.
React Solution
import { useState } from "react";
function WeatherApp() {
const [city, setCity] = useState("");
return (
<div>
<h1>Weather App</h1>
<input
type="text"
placeholder="Enter city"
value={city}
onChange={(e) => setCity(e.target.value)}
/>
<p>City: {city}</p>
</div>
);
}
export default WeatherApp;
Output
If the user enters Delhi:
Weather App
[ Delhi ]
City: Delhi
Explanation
The input is a controlled input because its value comes from React state.
const [city, setCity] = useState("");
The onChange event updates the state whenever the user types.
onChange={(e) => setCity(e.target.value)}
Concepts Covered
useState- Controlled input
onChange- User input
3. Store Weather Data in State
Problem Statement
Create state for weather information and display the city, temperature, and condition.
React Solution
import { useState } from "react";
function WeatherApp() {
const [weather, setWeather] = useState({
city: "Delhi",
temperature: 32,
condition: "Sunny"
});
return (
<div>
<h1>Weather App</h1>
<h2>{weather.city}</h2>
<p>Temperature: {weather.temperature}°C</p>
<p>Condition: {weather.condition}</p>
</div>
);
}
export default WeatherApp;
Output
Weather App
Delhi
Temperature: 32°C
Condition: Sunny
Explanation
The weather information is stored as an object inside state.
const [weather, setWeather] = useState({
city: "Delhi",
temperature: 32,
condition: "Sunny"
});
Each property can then be displayed using JSX.
Concepts Covered
- Object state
useState- JSX expressions
- Displaying dynamic data
4. Fetch Weather Data from an API
Problem Statement
Create a function that requests weather data from an API using fetch().
Use a placeholder API URL in the practice example.
React Solution
async function getWeather(city) {
const response = await fetch(
`https://example.com/weather?city=${encodeURIComponent(city)}`
);
if (!response.ok) {
throw new Error("Unable to fetch weather data");
}
const data = await response.json();
return data;
}
You can call the function like this:
async function searchWeather() {
try {
const data = await getWeather("Delhi");
console.log(data);
} catch (error) {
console.error(error.message);
}
}
Output
The exact output depends on the weather API being used.
For example:
{
city: "Delhi",
temperature: 32,
condition: "Sunny"
}
Explanation
fetch() sends a network request to the API.
const response = await fetch(url);
The response.ok check is important because fetch() does not automatically reject the Promise for HTTP errors such as 404 or 500.
The JSON response is converted into JavaScript data using:
const data = await response.json();
Concepts Covered
fetch()- API request
async/await- JSON
- HTTP error checking
5. Fetch Weather Data with useEffect
Problem Statement
Fetch weather information when a city is selected and store the response in React state.
React Solution
import { useEffect, useState } from "react";
function WeatherApp() {
const [city, setCity] = useState("Delhi");
const [weather, setWeather] = useState(null);
useEffect(() => {
async function loadWeather() {
try {
const response = await fetch(
`https://example.com/weather?city=${encodeURIComponent(city)}`
);
if (!response.ok) {
throw new Error("Weather request failed");
}
const data = await response.json();
setWeather(data);
} catch (error) {
console.error(error.message);
}
}
loadWeather();
}, [city]);
return (
<div>
<h1>Weather App</h1>
<p>City: {city}</p>
{weather && (
<p>
Temperature: {weather.temperature}°C
</p>
)}
</div>
);
}
export default WeatherApp;
Output
Weather App
City: Delhi
Temperature: 32°C
Explanation
The useEffect runs when the city value changes.
}, [city]);
The API request is performed inside the effect, and the returned data is stored using setWeather().
In a real application, replace the placeholder URL with the endpoint and request format of the weather API you choose.
Concepts Covered
useEffect- API integration
fetch()- Dependency array
- State updates
6. Add a Loading State
Problem Statement
Display a loading message while the weather API request is running.
React Solution
import { useEffect, useState } from "react";
function WeatherApp() {
const [city, setCity] = useState("Delhi");
const [weather, setWeather] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
async function loadWeather() {
setLoading(true);
try {
const response = await fetch(
`https://example.com/weather?city=${encodeURIComponent(city)}`
);
if (!response.ok) {
throw new Error("Weather request failed");
}
const data = await response.json();
setWeather(data);
} catch (error) {
console.error(error.message);
} finally {
setLoading(false);
}
}
loadWeather();
}, [city]);
return (
<div>
<h1>Weather App</h1>
{loading && <p>Loading weather...</p>}
{!loading && weather && (
<div>
<h2>{weather.city}</h2>
<p>{weather.temperature}°C</p>
</div>
)}
</div>
);
}
export default WeatherApp;
Output
While loading:
Weather App
Loading weather...
After the request:
Weather App
Delhi
32°C
Explanation
The loading state tells the user that the application is waiting for the API response.
finally is useful because it runs after both successful and failed requests.
finally {
setLoading(false);
}
Concepts Covered
- Loading state
- Conditional rendering
try/catch/finally- API request status
7. Handle Weather API Errors
Problem Statement
Display an error message when the weather request fails.
React Solution
import { useState } from "react";
function WeatherApp() {
const [error, setError] = useState("");
async function searchWeather() {
setError("");
try {
const response = await fetch(
"https://example.com/weather?city=Delhi"
);
if (!response.ok) {
throw new Error("Unable to get weather data");
}
const data = await response.json();
console.log(data);
} catch (error) {
setError(error.message);
}
}
return (
<div>
<h1>Weather App</h1>
<button onClick={searchWeather}>
Get Weather
</button>
{error && <p>{error}</p>}
</div>
);
}
export default WeatherApp;
Output
If the request fails:
Weather App
[ Get Weather ]
Unable to get weather data
Explanation
The error message is stored in state:
const [error, setError] = useState("");
When an error occurs, setError() updates the UI.
It is good practice to show a useful message instead of leaving the user wondering why no weather information appeared.
Concepts Covered
- Error state
try/catch- Conditional rendering
- API error handling
8. Display Temperature and Other Weather Details
Problem Statement
Create a weather card that displays city, temperature, humidity, and wind speed from weather state.
React Solution
function WeatherCard({ weather }) {
if (!weather) {
return <p>No weather data available.</p>;
}
return (
<div>
<h2>{weather.city}</h2>
<p>Temperature: {weather.temperature}°C</p>
<p>Humidity: {weather.humidity}%</p>
<p>Wind Speed: {weather.windSpeed} km/h</p>
<p>Condition: {weather.condition}</p>
</div>
);
}
export default WeatherCard;
Output
Delhi
Temperature: 32°C
Humidity: 55%
Wind Speed: 14 km/h
Condition: Sunny
Explanation
The weather card receives data through props.
<WeatherCard weather={weather} />
This keeps the weather display separate from the logic responsible for fetching data.
Concepts Covered
- Props
- Reusable components
- Conditional rendering
- Component separation
9. Search for a City and Handle Invalid Searches
Problem Statement
Create a search form where the user enters a city and clicks a button to request weather information. Display an error if the city field is empty.
React Solution
import { useState } from "react";
function WeatherApp() {
const [city, setCity] = useState("");
const [error, setError] = useState("");
async function searchWeather(e) {
e.preventDefault();
const trimmedCity = city.trim();
if (!trimmedCity) {
setError("Please enter a city name.");
return;
}
setError("");
try {
const response = await fetch(
`https://example.com/weather?city=${encodeURIComponent(
trimmedCity
)}`
);
if (!response.ok) {
throw new Error("City not found or weather data unavailable.");
}
const data = await response.json();
console.log(data);
} catch (error) {
setError(error.message);
}
}
return (
<div>
<h1>Weather App</h1>
<form onSubmit={searchWeather}>
<input
type="text"
value={city}
placeholder="Enter city"
onChange={(e) => setCity(e.target.value)}
/>
<button type="submit">
Search
</button>
</form>
{error && <p>{error}</p>}
</div>
);
}
export default WeatherApp;
Output
If the input is empty:
Please enter a city name.
If the city is valid:
Weather data is requested...
Explanation
The input is trimmed before sending the request:
const trimmedCity = city.trim();
This prevents a search containing only spaces.
encodeURIComponent() is also used so that city names are safely included in the URL.
Concepts Covered
- Form handling
- Controlled input
- Validation
trim()encodeURIComponent()- API errors
10. Build a Complete React Weather Application
Problem Statement
Build a complete React weather application that includes:
- City search
- Controlled input
- API request
- Loading state
- Error handling
- Weather information
- Clear weather result when a new search starts
Use a placeholder API endpoint and adapt the response fields to the weather API you select.
React Solution
import { useState } from "react";
function WeatherApp() {
const [city, setCity] = useState("");
const [weather, setWeather] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
async function searchWeather(e) {
e.preventDefault();
const trimmedCity = city.trim();
if (!trimmedCity) {
setError("Please enter a city name.");
setWeather(null);
return;
}
setLoading(true);
setError("");
setWeather(null);
try {
const response = await fetch(
`https://example.com/weather?city=${encodeURIComponent(
trimmedCity
)}`
);
if (!response.ok) {
throw new Error(
"Weather data could not be found for this city."
);
}
const data = await response.json();
setWeather({
city: data.city,
temperature: data.temperature,
condition: data.condition,
humidity: data.humidity,
windSpeed: data.windSpeed
});
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
}
return (
<div>
<h1>React Weather App</h1>
<form onSubmit={searchWeather}>
<input
type="text"
value={city}
placeholder="Enter city name"
onChange={(e) => setCity(e.target.value)}
/>
<button type="submit" disabled={loading}>
{loading ? "Searching..." : "Search"}
</button>
</form>
{error && (
<p>{error}</p>
)}
{loading && (
<p>Loading weather information...</p>
)}
{!loading && weather && (
<div>
<h2>{weather.city}</h2>
<p>
Temperature: {weather.temperature}°C
</p>
<p>
Condition: {weather.condition}
</p>
<p>
Humidity: {weather.humidity}%
</p>
<p>
Wind Speed: {weather.windSpeed} km/h
</p>
</div>
)}
</div>
);
}
export default WeatherApp;
Output
A successful search can produce:
React Weather App
[ Delhi ] [ Search ]
Delhi
Temperature: 32°C
Condition: Sunny
Humidity: 55%
Wind Speed: 14 km/h
While the request is running:
React Weather App
[ Delhi ] [ Searching... ]
Loading weather information...
If the request fails:
Weather data could not be found for this city.
Explanation
This example combines the major concepts from the chapter.
Step 1: Store the Input
const [city, setCity] = useState("");
The city entered by the user is stored in state.
Step 2: Store Weather Data
const [weather, setWeather] = useState(null);
The API response is stored after a successful request.
Step 3: Track Loading
const [loading, setLoading] = useState(false);
This allows the application to show a loading message and disable the search button while the request is running.
Step 4: Track Errors
const [error, setError] = useState("");
The application can show a useful message when the request fails.
Step 5: Validate the City
const trimmedCity = city.trim();
if (!trimmedCity) {
setError("Please enter a city name.");
return;
}
This prevents an empty search.
Step 6: Request Data
const response = await fetch(url);
The application sends a request to the weather API.
Step 7: Check the Response
if (!response.ok) {
throw new Error("Weather request failed.");
}
This handles HTTP errors.
Step 8: Display the Result
The weather information is displayed only when data is available.
{!loading && weather && (
<div>
...
</div>
)}
For a real application, replace the placeholder API URL with the weather service you choose and map its actual response fields to the properties used by the component.
If an API requires a secret credential, follow that provider’s security guidance. A value shipped to browser JavaScript should not be treated as a truly secret server-side credential.
Concepts Covered
- React components
useState- Controlled forms
- Form submission
fetch()async/await- API integration
- Loading state
- Error state
- Conditional rendering
- Props
- Reusable components
- Input validation
- JSON data
- HTTP error handling
Key Takeaways
- A React weather application is a good project for practicing API integration.
useStatecan store the city, weather data, loading state, and error state.- Controlled inputs keep form values connected to React state.
fetch()can be used to request weather data from an API.async/awaitmakes asynchronous API code easier to read.- Always check
response.okwhen handlingfetch()responses. - Loading states improve the user experience while waiting for API responses.
- Error states help users understand when a request fails.
- Weather information received from an API can be stored in state and displayed using JSX.
- Search results are normally derived from the latest API response rather than stored as unnecessary duplicate state.
- A production weather application can be extended with location detection, weather icons, forecasts, unit switching, caching, and better responsive design.
- API credentials that must remain secret should generally be handled on a trusted server rather than exposed in browser code.
FAQs
1. What is a React Weather Application?
A React Weather Application is a project that uses React to create a weather interface where users can search for a location and view weather information received from a weather API.
2. Which React concepts are used in a Weather Application?
Common concepts include components, useState, controlled inputs, event handling, conditional rendering, fetch(), async/await, and API integration.
3. How does React fetch weather data?
React can use JavaScript’s fetch() function to send a request to a weather API. The response can then be converted to JSON and stored in React state.
4. Why is useState used in a React Weather Application?
useState can store values such as the city entered by the user, weather data, loading status, and error messages so the UI updates when these values change.
5. How do you show a loading message in React Weather Application?
Create a loading state and conditionally render a message:
{loading && <p>Loading weather...</p>}
The state can be changed before and after the API request.
6. How do you handle an invalid city in a React Weather Application?
The application can check the API response and display an error message when the API reports that the location was not found or the request failed.
7. Can a React Weather Application get weather data without an API?
A real-time weather application normally needs a weather data source such as an API. Without an external data source, you can still build the React interface using static or locally stored sample weather data.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
