Students will create a React application where:
- The main page lists a few city options (e.g., "New York," "London," "Tokyo").
- Clicking on a city navigates to a forecast page using URL parameters (
useParams
). - The forecast page fetches mock weather data for the selected city using
useEffect
. - The application includes a button to scroll to the detailed weather section using
useRef
.
This activity will help students combine and practice useEffect
, useRef
, and useParams
.
npm install react-router-dom
📁 File Structure App.js: Main component to configure routes.
CityList.js: Component to list cities with links to the forecast page.
CityForecast.js: Component to display the forecast for the selected city.
App.js
: Main component to configure routes.CityList.js
: Component to list cities with links to the forecast page.CityForecast.js
: Component to display the forecast for the selected city.
Define mock data to simulate weather details:
const weatherData = {
NewYork: {
summary: "Sunny, 25°C",
details: "Clear skies throughout the day with mild temperatures.",
},
London: {
summary: "Cloudy, 18°C",
details: "Overcast with occasional light rain in the afternoon.",
},
Tokyo: {
summary: "Rainy, 22°C",
details: "Continuous rain expected throughout the day.",
},
};
- Display a list of cities with links to their forecast pages.
- Each city links to
/forecast/:cityName
usingLink
from React Router.
- Extract the city name from the URL using
useParams
. - Use
useEffect
to simulate fetching the weather data for the selected city. - Use
useRef
to scroll to the detailed weather section when a "View Details" button is clicked.
- Set up routes to display the city list at
/
. - Set up the forecast page at
/forecast/:cityName
.
- Display a fallback message if the
cityName
parameter does not match any city inweatherData
.
In CityForecast
, add a button to navigate back to the city list:
import { Link } from "react-router-dom";
<Link to="/">Back to City List</Link>
- Use CSS to improve the layout and appearance of the city list and forecast pages.