使用ReactJS的天气应用程序

使用ReactJS的天气应用程序

在本文中,我们将使用ReactJS框架开发一个交互式的天气应用程序。开发的应用程序将为用户提供搜索城市的实时天气信息。如果用户搜索了错误的城市,还会向用户显示错误信息,说明搜索的城市未找到。我们使用了OpenWeatherMap API,该API可以让我们获取全球各地的天气数据。我们已经获取了各个地点的天气信息,包括风速等。

让我们交互地看一下我们最终项目的样子:

使用ReactJS的天气应用程序

使用的技术/先决条件:

  • ReactJS
  • CSS
  • JSX
  • React中的函数组件

方法:

开发的代码使用ReactJS框架显示交互式天气应用程序。该应用程序允许用户实时获取各个城市的信息。借助API,我们可以获取用户搜索的城市的天气详情。该应用程序完全响应式,输出的响应时间也非常快。用户也可以轻松导航到应用程序的组件。用户界面完全用户友好,用户可以轻松操作应用程序。我们使用了各种图标,使我们开发的应用程序更具吸引力。

项目结构:

使用ReactJS的天气应用程序

package.json中的依赖项看起来是这样的: 这样:

"dependencies": {  
    "@fortawesome/free-solid-svg-icons": "^6.4.2",  
    "@fortawesome/react-fontawesome": "^0.2.0",  
    "@testing-library/jest-dom": "^5.17.0",  
    "@testing-library/react": "^13.4.0",  
    "@testing-library/user-event": "^13.5.0",  
    "axios": "^1.4.0",  
    "react": "^18.2.0",  
    "react-dom": "^18.2.0",  
    "react-loader-spinner": "^5.3.4",  
    "react-scripts": "5.0.1",  
    "web-vitals": "^2.1.4"  
}  
JavaScript

创建应用的步骤:

步骤1:VSCode IDE中使用以下命令设置React项目。

npx create-react-app <<name of project>>  
JavaScript

步骤2: 执行以下命令,进入新创建的项目文件夹。

cd <<Name_of_project>>  
JavaScript

步骤3: 由于我们在项目中使用了各种包,我们需要安装它们。使用以下命令安装package.json文件中指定的所有包。

npm install axios react-loader-spinner @fortawesome/react-fontawesome @fortawesome/free-solid-svg-icons  
JavaScript

示例: 将下面的代码插入到相应的文件中。

  • App.js: 所有在应用程序中使用的逻辑都以编程方式编写在这个文件中。从这个文件中,所有的按钮、卡片和图标都在web浏览器中呈现。
  • App.css 这个文件包含所有的样式代码,无论是h1标签的样式还是背景样式。应用程序的所有外观和感觉都在这个样式文件中指定。
//App.js 
  
import { Oval } from 'react-loader-spinner'; 
import React, { useState } from 'react'; 
import axios from 'axios'; 
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; 
import { faFrown } from '@fortawesome/free-solid-svg-icons'; 
import './App.css'; 
  
function GfGWeatherApp() { 
    const [input, setInput] = useState(''); 
    const [weather, setWeather] = useState({ 
        loading: false, 
        data: {}, 
        error: false, 
    }); 
  
    const toDateFunction = () => { 
        const months = [ 
            'January', 
            'February', 
            'March', 
            'April', 
            'May', 
            'June', 
            'July', 
            'August', 
            'September', 
            'October', 
            'November', 
            'December', 
        ]; 
        const WeekDays = [ 
            'Sunday', 
            'Monday', 
            'Tuesday', 
            'Wednesday', 
            'Thursday', 
            'Friday', 
            'Saturday', 
        ]; 
        const currentDate = new Date(); 
        const date = `{WeekDays[currentDate.getDay()]}{currentDate.getDate()} {months[currentDate.getMonth()] 
            }`; 
        return date; 
    }; 
  
    const search = async (event) => { 
        if (event.key === 'Enter') { 
            event.preventDefault(); 
            setInput(''); 
            setWeather({ ...weather, loading: true }); 
            const url = 'https://api.openweathermap.org/data/2.5/weather'; 
            const api_key = 'f00c38e0279b7bc85480c3fe775d518c'; 
            await axios 
                .get(url, { 
                    params: { 
                        q: input, 
                        units: 'metric', 
                        appid: api_key, 
                    }, 
                }) 
                .then((res) => { 
                    console.log('res', res); 
                    setWeather({ data: res.data, loading: false, error: false }); 
                }) 
                .catch((error) => { 
                    setWeather({ ...weather, data: {}, error: true }); 
                    setInput(''); 
                    console.log('error', error); 
                }); 
        } 
    }; 
  
    return ( 
        <div className="App"> 
            <h1 className="app-name"> 
                GeeksforGeeks Weather App 
            </h1> 
            <div className="search-bar"> 
                <input 
                    type="text"
                    className="city-search"
                    placeholder="Enter City Name.."
                    name="query"
                    value={input} 
                    onChange={(event) => setInput(event.target.value)} 
                    onKeyPress={search} 
                /> 
            </div> 
            {weather.loading && ( 
                <> 
                    <br /> 
                    <br /> 
                    <Oval type="Oval" color="black" height={100} width={100} /> 
                </> 
            )} 
            {weather.error && ( 
                <> 
                    <br /> 
                    <br /> 
                    <span className="error-message"> 
                        <FontAwesomeIcon icon={faFrown} /> 
                        <span style={{ fontSize: '20px' }}>City not found</span> 
                    </span> 
                </> 
            )} 
            {weather && weather.data && weather.data.main && ( 
                <div> 
                    <div className="city-name"> 
                        <h2> 
                            {weather.data.name}, <span>{weather.data.sys.country}</span> 
                        </h2> 
                    </div> 
                    <div className="date"> 
                        <span>{toDateFunction()}</span> 
                    </div> 
                    <div className="icon-temp"> 
                        <img 
                            className=""
                            src={`https://openweathermap.org/img/wn/{weather.data.weather[0].icon}@2x.png`} 
                            alt={weather.data.weather[0].description} 
                        /> 
                        {Math.round(weather.data.main.temp)} 
                        <sup className="deg">°C</sup> 
                    </div> 
                    <div className="des-wind"> 
                        <p>{weather.data.weather[0].description.toUpperCase()}</p> 
                        <p>Wind Speed: {weather.data.wind.speed}m/s</p> 
                    </div> 
                </div> 
            )} 
        </div> 
    ); 
} 
  
export default GfGWeatherApp;
JavaScript

CSS

/* App.css */
* { 
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, 
        Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 
} 
  
html { 
    background-color: #f7f7f7; 
} 
  
.app-name { 
    font-size: 2.3rem; 
    color: rgb(17, 144, 0); 
    margin-bottom: 16px; 
} 
  
.App { 
    display: flex; 
    flex-direction: column; 
    justify-content: center; 
    align-items: center; 
    width: 600px; 
    min-height: 440px; 
    background-color: rgb(255, 255, 255); 
    text-align: center; 
    margin: 128px auto; 
    border-radius: 10px; 
    padding-bottom: 32px; 
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); 
} 
  
.city-search { 
    width: 100%; 
    max-width: 400px; 
    box-sizing: border-box; 
    border: 2px solid rgb(204, 204, 204); 
    outline: none; 
    border-radius: 20px; 
    font-size: 16px; 
    background-color: #e5eef0; 
    background-position: 10px 12px; 
    background-repeat: no-repeat; 
    padding: 12px 40px 12px 40px; 
    -webkit-transition: width 0.4s ease-in-out; 
    transition: width 0.4s ease-in-out; 
    color: #333; 
} 
  
.city-search:focus { 
    width: 100%; 
} 
  
.city-name { 
    font-size: 1.5rem; 
    color: #444; 
    margin-bottom: 8px; 
} 
  
.date { 
    font-size: 1.25em; 
    font-weight: 500; 
    color: #777; 
} 
  
.icon-temp { 
    font-size: 3rem; 
    font-weight: 700; 
    color: #1e2432; 
    text-align: center; 
} 
  
.deg { 
    font-size: 1.3rem; 
    vertical-align: super; 
} 
  
.des-wind { 
    font-weight: 500; 
    color: #666; 
} 
  
.error-message { 
    display: block; 
    text-align: center; 
    color: #d32f2f; 
    font-size: 24px; 
    margin-top: auto; 
} 
  
.Loader { 
    display: flex; 
    justify-content: center; 
    align-items: center; 
    height: 100%; 
} 
  
.Loader>div { 
    margin: 0 auto; 
} 
  
.weather-icon { 
    display: flex; 
    justify-content: center; 
    align-items: center; 
} 
  
.weather-icon img { 
    width: 100px; 
    height: 100px; 
    border-radius: 50%; 
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); 
}
JavaScript

步骤5: 添加其他配置文件,如index.js。

运行应用程序的步骤:

1. 在终端中执行以下命令。

npm start
JavaScript

2. 打开Web浏览器,然后在地址栏中输入以下URL。

http://localhost:3000/
JavaScript

输出:

使用ReactJS的天气应用程序

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册