Steps to create our Weather Forecast App
Step 1: Create a React Native app by using this command:
npx create-expo-app WeatherApp
Step 2: Navigate to our project through this command:
cd WeatherApp
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react-native-paper": "4.9.2",
"@expo/vector-icons": "^13.0.0"
}
Example: Write the following code in the respective file.
Javascript
// Weather.js import React, { useState } from 'react' ; import { View, Text, Pressable, TextInput } from 'react-native' ; import { styles } from './styles' ; import { getWeather, getForecast } from './api' ; const Weather = () => { const [city, setCity] = useState( "" ); const [weatherData, setWeatherData] = useState( null ); const [forecastData, setForecastData] = useState( null ); const handleGetWeather = () => { getWeather(city, setWeatherData, setForecastData); }; const handleGetForecast = () => { getForecast(city, setWeatherData, setForecastData); }; return ( <View style={styles.centeredContent}> <Text style={styles.title}>w3wiki</Text> <Text style={styles.title}>Weather App</Text> <TextInput style={styles.input} placeholder= "Enter city name" value={city} onChangeText={setCity} /> <Pressable onPress={handleGetWeather} style={({ pressed }) => [ styles.button, { backgroundColor: pressed ? '#1e8449' : '#2ecc71' , }, ]} > <Text style={styles.buttonText}>Get Weather</Text> </Pressable> <Text> </Text> <Pressable onPress={handleGetForecast} style={({ pressed }) => [ styles.button, { backgroundColor: pressed ? '#1e8449' : '#2ecc71' , }, ]} > <Text style={styles.buttonText}>Get Forecast</Text> </Pressable> {weatherData && ( <View style={styles.weatherInfo}> <Text style={styles.weatherText}> <Text style={styles.heading}> Temperature: </Text> {weatherData.temperature} °C </Text> <Text style={styles.weatherText}> <Text style={styles.heading}> Description: </Text> {weatherData.description} </Text> </View> )} {forecastData && ( <View style={styles.weatherInfo}> <Text style={styles.heading}> Forecast for the next few hours: { '\n' } </Text> {forecastData.map((forecastItem, index) => ( <Text key={index} style={styles.weatherText}> <Text style={styles.subheading}>Time:</Text>{ ' ' } { new Date(forecastItem.dt * 1000).toLocaleTimeString()},{ ' ' } <Text style={styles.subheading}>Temperature:</Text>{ ' ' } {(forecastItem.main.temp - 273.15).toFixed(2)} °C,{ ' ' } <Text style={styles.subheading}>Description:</Text>{ ' ' } {forecastItem.weather[0].description} </Text> ))} </View> )} </View> ); }; export default Weather; |
Javascript
// api.js import { Alert } from "react-native" ; export const getWeather = async (city, setWeatherData, setForecastData) => { try { const apiKey = 'YOUR_API_KEY' ; // Replace with your OpenWeatherMap API key const apiUrl = `https: //api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`; const response = await fetch(apiUrl); const data = await response.json(); // Check if the response contains an error message if (data.cod && data.cod !== 200) { throw new Error(data.message || 'Failed to fetch weather data' ); } // Extract temperature and weather description from the API response const temperatureKelvin = data.main.temp; // Convert to Celsius const temperatureCelsius = (temperatureKelvin - 273.15).toFixed(2); const description = data.weather[0].description; setForecastData( null ); setWeatherData({ temperature: temperatureCelsius, description }); } catch (error) { console.error( 'Error fetching weather data:' , error.message); Alert.alert( 'Error' , 'Failed to fetch weather data. Please try again.' ); } }; export const getForecast = async (city, setWeatherData, setForecastData) => { try { const apiKey = 'YOUR_API_KEY' ; // Replace with your OpenWeatherMap API key const apiUrl = `https: //api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}`; const response = await fetch(apiUrl); const data = await response.json(); // Check if the response contains an error message if (data.cod && data.cod !== '200' ) { throw new Error(data.message || 'Failed to fetch forecast data' ); } // Extract relevant forecast information from the API response const forecast = data.list.slice(0, 3); // Get forecast for the next few hours setWeatherData( null ); setForecastData(forecast); } catch (error) { console.error( 'Error fetching forecast data:' , error.message); Alert.alert( 'Error' , 'Failed to fetch forecast data. Please try again.' ); } }; |
Javascript
// App.js import React from 'react' ; import { View } from 'react-native' ; import Weather from './Weather' ; import { styles } from './styles' ; const App = () => { return ( <View style={styles.container}> <Weather /> </View> ); }; export default App; |
Javascript
// styles.js import { StyleSheet } from 'react-native' ; export const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center' , }, centeredContent: { alignItems: 'center' , }, title: { fontSize: 24, fontWeight: 'bold' , color: '#228B22' , marginBottom: 20, }, input: { height: 40, width: '80%' , borderColor: '#228B22' , borderWidth: 1, borderRadius: 5, paddingHorizontal: 10, marginBottom: 20, color: '#228B22' , }, button: { flexDirection: 'row' , alignItems: 'center' , backgroundColor: '#228B22' , padding: 10, borderRadius: 5, }, buttonText: { color: 'white' , marginLeft: 10, }, weatherInfo: { marginTop: 20, alignItems: 'center' , }, heading: { fontSize: 18, fontWeight: 'bold' , color: '#228B22' , marginTop: 10, }, subheading: { fontSize: 16, fontWeight: 'bold' , color: '#228B22' , marginTop: 10, }, weatherText: { color: '#228B22' , fontSize: 16, marginBottom: 8, }, }); |
Steps to run the application:
Step 1: Type the following command in terminal
npx expo start
Step 2: Depending on your operating system, type the following command
- To run on Android:
npx react-native run-android
- To run on Ios:
npx react-native run-ios
Output:
Note: You can also download the Expo Go app from the Apple App Store (For iOS) or Google Play Store (For Android) to run the app.
Create a Weather App with Forecast using React-Native
React-Native is an open-source framework used to develop cross-platform applications i.e., you can write code in React-Native and publish it as an Android or IOS app. In this article, we will build a weather app using React-Native.
The app contains two features:
- Getting the current weather of a given city
- Getting the weather forecast for the next few hours.
Preview of the Final Output: Let us have a look at how the final application will look like.