🌐
50 React Coding Puzzles
  • 50 React Coding Puzzles
  • Contact
  • Reviews
  • Table of Contents
  • Introduction
  • 1 - Simple Counter App
  • 2 - Dynamic List of Items with Strikethrough
  • 3 - Color Picker with Hex Code Display
  • 4 - Password Strength Checker
  • 5 - Countdown Timer with Audio
  • 6 - Dynamic Movie List with Filtering and Sorting
  • 7 - Text Animation Component (Fade/Scroll)
  • 8 - Dynamically Generated Text Art
  • 9 - Meme Generator with Custom Text
  • 10 - "What Should I Eat?" Random Recipe Generator
  • 11 - Simple Quiz App with Multiple Choice
  • 12 - Unit Converter
  • 13 - Dynamic Image Gallery with Lightbox
  • 14 - Weather Widget with Temperature and Description
  • 15 - Contact Form with Email and Message Validation
  • 16 - Color Palette Generator
  • 17 - Drag-and-Drop Feature for Rearranging Items
  • 18 - Interactive Quiz with Dynamic Results and Feedback
  • 19 - To-Do List with Task Categorization
  • 20 - Note-Taking App with Markdown Support
  • 21 - Simple Calculator with Basic Operations
  • 22 - Word Scramble Game with Timer and Score
  • 23 - Number Guessing Game
  • 24 - Digital Clock with Time Zone Support
  • 25 - Interactive Time Zone Converter
  • 26 - Weather Forecast App with Location Detection
  • 27 - Real-Time Stock Ticker with Updates
  • 28 - Virtual Dice Roller with Multiple Dice
  • 29 - Responsive Navigation Menu with Dropdowns
  • 30 - Progress Bar for Loading or Task Completion
  • 31 - Modal Window for Alerts and Confirmations
  • 32 - Infinite Scroll for Loading More Content
  • 33 - Form Validation with Error Messages
  • 34 - Search Bar with Filtering and Suggestions
  • 35 - Drag-and-Drop File Upload
  • 36 - Interactive Color Picker with Sliders
  • 37 - Image Carousel with Autoplay
  • 38 - Rating System with Stars or Thumbs Up/Down
  • 39 - Comment Section with Nested Replies
  • 40 - Pagination for Long Lists of Data
  • 41 - Stopwatch app that tracks elapsed time
  • 42 - Responsive E-commerce Product Grid
  • 43 - Random Movie/Book Recommender
  • 44 - Kanban board for managing tasks with drag-and-drop
  • 45 - Chat application with real-time messaging using WebSockets
  • 46 - Calendar that displays events and allows scheduling
  • 47 - Tic-Tac-Toe Game
  • 48 - Hangman Game
  • 49 - Notes App
  • 50 - Expense Tracker
  • Afterword
  • Appendix
Powered by GitBook
On this page
  • Algorithm
  • Classes
  • Code
  • Explanation
  • Possible Future Enhancements

26 - Weather Forecast App with Location Detection

Description:

Create a React application that provides a weather forecast app with location detection. The app should automatically detect the user's location, allow users to manually enter a location if desired, fetch weather data from a weather API based on the chosen location, and display the current weather conditions, including temperature, humidity, wind speed, and weather description.

Algorithm

  1. Create a state variable to store the user's location and weather data.

  2. Define a function to automatically detect the user's location using the Geolocation API.

  3. Define a function to handle manual location input.

  4. Define a function to fetch weather data from a weather API based on the chosen location.

  5. Define a function to display the current weather conditions.

  6. Render the weather forecast app interface.

Classes

  • WeatherForecastApp: A component that represents the weather forecast app interface.

  • LocationDetector: A component that represents the location detection functionality.

  • WeatherDataFetcher: A component that represents the weather data fetching functionality.

  • WeatherConditionsDisplay: A component that represents the weather conditions display.

Code

WeatherForecastApp.js

import React, { useState, useEffect } from 'react';
import LocationDetector from './LocationDetector';
import WeatherDataFetcher from './WeatherDataFetcher';
import WeatherConditionsDisplay from './WeatherConditionsDisplay';

function WeatherForecastApp() {
  const [location, setLocation] = useState('');
  const [weatherData, setWeatherData] = useState({});

  useEffect(() => {
    const detectLocation = async () => {
      const userLocation = await LocationDetector.detectLocation();
      setLocation(userLocation);
    };
    detectLocation();
  }, []);

  const handleManualLocationInput = (location) => {
    setLocation(location);
  };

  const fetchWeatherData = async () => {
    const weatherData = await WeatherDataFetcher.fetchWeatherData(location);
    setWeatherData(weatherData);
  };

  useEffect(() => {
    fetchWeatherData();
  }, [location]);

  return (
    <div>
      <h2>Weather Forecast App</h2>
      <LocationDetector onLocationDetect={handleManualLocationInput} />
      <WeatherDataFetcher />
      <WeatherConditionsDisplay weatherData={weatherData} />
    </div>
  );
}

export default WeatherForecastApp;

LocationDetector.js

import React from 'react';

function LocationDetector({ onLocationDetect }) {
  const handleDetectLocation = async () => {
    const userLocation = await navigator.geolocation.getCurrentPosition(
      (position) => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        const location = `${latitude}, ${longitude}`;
        onLocationDetect(location);
      }
    );
  };

  return (
    <button onClick={handleDetectLocation}>
      Detect Location
    </button>
  );
}

export default LocationDetector;

WeatherDataFetcher.js

import React from 'react';
import axios from 'axios';

function WeatherDataFetcher() {
  const fetchWeatherData = async (location) => {
    const apiURL = `<weather-url`>;
    const response = await axios.get(apiURL);
    const weatherData = response.data;
    return weatherData;
  };

  return <div />;
}

export default WeatherDataFetcher;

WeatherConditionsDisplay.js

import React from 'react';

function WeatherConditionsDisplay({ weatherData }) {
  const temperature = weatherData.temp_c;
  const humidity = weatherData.humidity;
  const windSpeed = weatherData.wind_mph;
  const weatherDescription = weatherData.condition.text;

  return (
    <div>
      <h3>Current Weather Conditions</h3>
      <p>Temperature: {temperature}°C</p>
      <p>Humidity: {humidity}%</p>
      <p>Wind Speed: {windSpeed} mph</p>
      <p>Weather Description: {weatherDescription}</p>
    </div>
  );
}

export default WeatherConditionsDisplay;

Explanation

The WeatherForecastApp component renders the weather forecast app interface. The LocationDetector component detects the user's location using the Geolocation API. The WeatherDataFetcher component fetches weather data from a weather API based on the chosen location. The WeatherConditionsDisplay component displays the current weather conditions.

Possible Future Enhancements

  • Add more weather data to the display, such as precipitation and UV index.

  • Improve the user interface and user experience.

  • Add support for multiple weather APIs.

  • Allow users to save their favorite locations for quick access.

  • Display weather forecasts for multiple days.

Previous25 - Interactive Time Zone ConverterNext27 - Real-Time Stock Ticker with Updates

Last updated 10 months ago