Open In App

Create a Real-Time Weather Forecast App with React

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Real-time weather forecast app with React involves integrating with a weather API to fetch weather data and display it in the UI. Individuals can use the app to check the current weather conditions, temperature, humidity, and other relevant weather data for their location or any city they are interested in. It helps them plan outdoor activities, clothing choices, and travel arrangements accordingly.

Output Preview: Let us have a look at how the final output will look like.

weather

Prerequisites:

Steps to Create Real-Time Weather Forecast React App:

Step 1: Set up a new React project using React.js

npx create-react-app weather-app
cd weather-app

Step 2: Installing the Modules.

npm install axios
npm install bootstrap

Step 3: Create an account on openweathermap

Step 4: Then you will be directed to API Documentation’s page, Choose the api url from there and copy it:

Step 5: You can create the API Key using with the link given in the documentation, Get your API Key and copy it.

Step 6: Create a folder called components in src directory and create the following files inside it Add WeatherComponet.js , WeatherService.js.

Project Structure:
Wea1List

The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.7",
"bootstrap": "^5.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Approach to create Real-Time Weather Forecast App:

  • App.js: App.js is typically the main entry point of a React application. It serves as the root component where other components are composed together.
  • WeatherComponent.js: WeatherComponent.js is a React component responsible for fetching and displaying weather data. It interacts with the user to input a city name and then fetches the weather information for that city from an API.
  • DateSelector.js: This component can be a dropdown menu, a calendar picker, or any other UI element that suits your design.

Example: Modify the following code to create the Real-Time Weather Forecast App.

Javascript




// App.js
import React from 'react';
import WeatherComponent
    from './components/WeatherComponent';
import './App.css';
 
function App() {
    return (
        <div className="App">
            <header className="App-header">
                <h1>
                    Real-time Weather Forecast App
                </h1>
            </header>
            <main>
                <WeatherComponent />
            </main>
            <footer>
                <p>
                    Â© 2024 Weather App Inc.
                    All rights reserved.
                </p>
            </footer>
        </div>
    );
}
 
export default App;


Javascript




// WeatherComponents.js
 
import React,
{
    useState,
    useEffect
} from 'react';
import axios from 'axios';
import DateSelector from './DateSelector';
import 'bootstrap/dist/css/bootstrap.min.css';
 
const WeatherForecastApp = () => {
    const [city, setCity] = useState('');
    const [selectedDate, setSelectedDate] = useState('');
    const [forecastData, setForecastData] = useState(null);
    const [filteredForecast, setFilteredForecast] = useState([]);
    const [error, setError] = useState(null);
 
    useEffect(() => {
        const fetchForecastData = async () => {
            try {
                const response =
                    await axios.get(
`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=643d6c8f0049d7732aab38687b0f0807&units=metric`
                    );
                setForecastData(response.data);
                setError(null);
            } catch (error) {
                setError(
                    `Error fetching weather
                     data. Please try again.`
                );
                setForecastData(null);
            }
        };
 
        if (city) {
            fetchForecastData();
        }
    }, [city]);
 
    useEffect(() => {
        if (forecastData && selectedDate) {
            const filteredData =
                forecastData.list.filter(
                    forecast =>
                        forecast.dt_txt.includes(selectedDate)
                );
            setFilteredForecast(filteredData);
        }
    }, [forecastData, selectedDate]);
 
    const handleCityChange = (e) => {
        setCity(e.target.value);
    };
 
    const handleDateChange = (date) => {
        setSelectedDate(date);
    };
 
    return (
        <div className="weather-forecast-app container mt-4">
            <h1>Weather Forecast</h1>
            <center className="form-group">
                <label htmlFor="city">
                    Enter City:
                </label>
                <input type="text" className="form-control"
                    id="city" value={city}
                    onChange={handleCityChange} />
            </center>
            <DateSelector onDateChange={handleDateChange} />
            {error && <p>{error}</p>}
            {
                filteredForecast.length > 0 && (
                    <div className="row forecast-container">
                        {filteredForecast.map((forecast, index) => (
                            <div key={index} className="col-md-3">
                                <div className="card mb-3">
                                    <div className="card-body">
                                        <h5 className="card-title">
                                            Date: {forecast.dt_txt}
                                        </h5>
                                        <p className="card-text">
                                            Temperature:
                                            {forecast.main.temp} °C
                                        </p>
                                        <p className="card-text">
                                            Weather:
                                            {forecast.weather[0].description}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
        </div>
    );
};
 
export default WeatherForecastApp;


Javascript




// DateSelector.js
import React,
{
    useState
} from 'react';
 
const DateSelector = ({ onDateChange }) => {
    const [selectedDate, setSelectedDate] = useState('');
 
    const handleDateChange = (e) => {
        const date = e.target.value;
        setSelectedDate(date);
        onDateChange(date);
    };
 
    return (
        <div>
            <label htmlFor="date">
                Select Date:
            </label>
            <input type="date" id="date"
                value={selectedDate}
                onChange={handleDateChange} />
        </div>
    );
};
 
export default DateSelector;


CSS




/* App.css */
 
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f2f2f2;
}
 
.App {
    text-align: center;
    margin: 0 auto;
    padding: 20px;
}
 
.App-header {
    background-color: #4CAF50;
    color: white;
    padding: 20px 0;
}
 
.App-header h1 {
    margin: 0;
}
 
/* Adjust input styling */
input[type="text"] {
    padding: 10px;
    /* Increased padding */
    margin: 10px 0;
    width: 300px;
    /* Increased width */
    border-radius: 5px;
    border: 1px solid #ccc;
    box-sizing: border-box;
    /* Added box-sizing */
}
 
button {
    padding: 10px 20px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
 
button:hover {
    background-color: #45a049;
}
 
.weather-container {
    margin-top: 20px;
    background-color: #fff;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
 
.weather-container h2 {
    margin-bottom: 10px;
}
 
.weather-info {
    display: flex;
    flex-wrap: wrap;
    /* Added flex-wrap property */
    justify-content: space-between;
}
 
.weather-info .card {
    width: 48%;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
}
 
.weather-info p {
    margin: 5px 0;
}
 
.footer {
    margin-top: 20px;
    padding: 10px;
    background-color: #333;
    color: white;
    position: fixed;
    bottom: 0;
    width: 100%;
}


Steps to Run the App:

npm start

Output: Open web-browser and type the following URL http://localhost:3000/

ezgifcom-video-to-gif-converter

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads