Building a React Native App- Weather App
React Native framework has been developed to support cross-platform app development. From this tutorial blog, you will learn how to make a weather forecasting app that every react native development company adopts.
Most importantly, I will provide the entire code snippet at the end of this blog tutorial. So stay tuned.
Before starting this tutorial, I suggest you learn about the React Native app development tool: Expo CLI. Here, I have used the Expo CLI tool to build the app.
You can check this article on ‘What should be chosen in react native Cli or Expo Cli?’ to get a fair understanding of both the tools namely React Native CLI and Expo CLI.
If you are already aware of these tools and their usage, you can skip this part and move ahead.
Now we will discuss the criteria you need to have a strong hold on.
Pre-conditions to be achieved
Getting started with the app-building process
Here, you will learn about making changes in the app screen, adding icons, changing default texts, and others.
Creating a basic app
You have to start with a small ‘Hello world’ app. For this, run the command npx create-expo-app weather-app
on a new terminal. This will let you build a react native expo app named ‘weather-app’.
This is the base app, where you have to add components, elements, images, icons, texts, and other objects. Search for the app on the search bar of your system and then open the VS code editor from the app folder.
Designing the first loading screen
Now you have to make changes in the ./app.js
folder. Go to the ./app.js
folder and find the text element stating “Open up App.js to start working on your app!”
. Change this into a different sentence.
Since this is a weather forecasting app, I have added a sentence “Welcome to the Weather forecasting app”
. The change in output will be similar to as given in image 1.
You can also change the splash screen and add different images to the first loading screen by adding square-sized images to the project’s ./asset
folder.
Utility of the React Native hook- isLoading state
As the project requires the data fetching process. You have to use the isLoading
state. It can be given two values either true or false.
If you set the isLoading
state as true, it will imply that the data isLoading
and will take time to display on the screen.
On the other hand, if you set it as false, it will imply that the data has been called and is not loading.
Let’s see how you can use the isLoading
state in your codebase and what can be the output.
Consider the following code syntax
state = {
isLoading: false
};
render() {
const { isLoading } = this.state;
return (
<View style={styles.container}>
{isLoading ? null : (
<View>
<Text>Welcome to the Weather forecasting app.</Text>
Here, what the syntax specifies isLoading state is false and it will render the text “Welcome to the Weather forecasting app”
on the screen. It implies the data which is called is not in the loading state.
Now let’s see what happens if it is true. Consider the below-give code syntax
state = {
isLoading: true
};
render() {
const { isLoading } = this.state;
return (
<View style={styles.container}>
{isLoading ? (
<Text>Please wait, while it is collecting the weather-based data.</Text>
Here, the state of the isLoading
hook is true. I have designed the code in a manner that the app screen will show the text “Please wait, while it is collecting the weather-based data.”
when the isLoading
is true. I have integrated the <Text>
component under the <View>
component.
You can again change it to false when it is done loading. As you can get the concept of using the isLoading
state for calling the weather-based data and showing it on the app screen when the isLoading
the state is false.
Adding the component folder and weather.js file
In this step, I will explain the process of adding icons, texts, and the temperature on the live weather app screen.
import React from "react";
import {View, Text, StyleSheet} from "react-native";
import { Feather } from "@expo/vector-icons";
const Weather = () => {
return (
<View style={styles.weatherContainer}>
<View style={styles.titleContainer}>
<Feather name="cloud-snow" size={58} color="#00ffff" />
<Text style={styles.tempText}>Live temperature </Text>
</View>
<View style={styles.bodyContainer}>
<Text style={styles.title}>So Chilled outside!!</Text>
<Text style={styles.subtitle}>My hands are getting cold.</Text>
</View>
</View>
);
};
Firstly, I imported the Feather
icon from the @expo/vector-icons
. Later in the codebase, you can see I used the icon with a font size of 58 and colored with #00ffff.
You need to include it under the titleContainer
to display it in the header. I have also added another text element “Live temperature” in the header, defined under the titleContainer
.
For the bodyContainer
, I have added two text elements a title
and a subtitle
. Refer to image 2 for the output.
API calling for the live temperature
Here, you will need a specific API key to fetch the live data of weather. Even though building an API is a backend task, I will show you an easy process to get the key.
Go to the site https://openweathermap.org/ and open the API section to access the default key.
Refer to the below-given code syntax where I have used the API key to get the live update on the weather.
Complete code syntax
import React, { useState, useEffect } from "react";
import { Platform, Text, View, StyleSheet } from "react-native";
import * as Location from "expo-location";
const API_KEY = "5bd2e0405c5b05e7f1dcda04a58619b5";
export default function App() {
const [location, setLocation] = useState(null);
const [weatherData, setWeatherData] = useState(null);
const [loaded, setLoaded] = useState(true);
useEffect(() => {
const DataLocation = async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== "granted") {
setErrorMsg("Permission to access location was denied");
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
console.log(location, "tanusree");
};
DataLocation();
}, []);
async function fectWeatherData(location) {
let lat = location.coords.latitude;
let long = location.coords.longitude;
console.log(lat, long);
setLoaded(false);
const API = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${API_KEY}&units=metric`;
console.log(API);
try {
const response = await fetch(API);
if (response.status == 200) {
const data = await response.json();
console.log(data, "12");
setWeatherData(data);
} else {
setWeatherData(null);
}
setLoaded(true);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
fectWeatherData(location);
console.log(weatherData, "345");
}, [location]);
return (
<View style={styles.weatherContainer}>
<View style={styles.headerContainer}>
<Text style={styles.tempText}>
{weatherData && weatherData.main.temp}˚
</Text>
</View>
<View
style={{
flex: 1,
justifyContent: "flex-end",
marginLeft: 30,
marginBottom: 40,
}}
>
<Text style={{ fontSize: 40, color: "#FFFFFF" }}>
{weatherData && weatherData.weather[0].main}
</Text>
<Text style={{ fontSize: 20, color: "#FFFFFF" }}>
{weatherData && weatherData.weather[0].description}
</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
weatherContainer: {
flex: 1,
backgroundColor: "orange",
},
headerContainer: {
flexDirection: "row",
marginTop: 100,
justifyContent: "space-around",
},
tempText: {
fontSize: 72,
color: "#FFFFFF",
},
});
You need to add the entire code snippet in the ./app.js
folder of the app’s root directory. Refer to image 3 for the output.
Final thoughts
If you are unable to start the emulator, you can run the command npm start
. It will allow you to start the bundling process on the emulator.
In case the issue persists, you have to make changes in the emulator in the Android studio. So let’s start coding now.