How to Create a Weather App with React Native

React Native is a popular framework for building cross-platform mobile applications using JavaScript and React. In this tutorial, you will learn how to create a weather app with React Native that can display the current weather conditions in your location.

Prerequisites

Before we begin, make sure you have the following software installed on your machine:

  • Node.js
  • npm or Yarn
  • React Native CLI

You also need to have a basic understanding of JavaScript and React.

Step 1: Set Up a New React Native Project

To get started, open your terminal and run the following command to create a new React Native project:

npx react-native init WeatherApp

This will create a new directory called WeatherApp with all the necessary files and dependencies.

Step 2: Set Up an OpenWeatherMap Account

To fetch weather data for our app, we will be using the OpenWeatherMap API. To get started, go to the OpenWeatherMap website and sign up for a free account.

Once you have an account, navigate to your account dashboard and obtain an API key. This key will allow you to make requests to the OpenWeatherMap API.

Step 3: Install Dependencies

Next, navigate to the project directory by running:

cd WeatherApp

Now, install the required dependencies by running the following command:

npm install axios react-native-geolocation-service

The axios library will be used to make HTTP requests to the OpenWeatherMap API, and react-native-geolocation-service library will help us retrieve the user’s location.

Step 4: Set Up Permissions

In order to retrieve the user’s location, we need to request the necessary permissions. Open the android/app/src/main/AndroidManifest.xml file and add the following lines before the closing </manifest> tag:

<uses-permission android_name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android_name="android.permission.ACCESS_COARSE_LOCATION" />

Next, open the ios/WeatherApp/Info.plist file and add the following lines before the closing </dict> tag:

<key>NSLocationWhenInUseUsageDescription</key>
<string>Allow access to your location to show weather information.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Allow access to your location to show weather information.</string>

With these permissions in place, the app will be able to request the user’s location.

Step 5: Create a Weather API Wrapper

In the project directory, create a new file called api.js inside a directory called src. This file will contain a wrapper function to make API requests to OpenWeatherMap.

Open the src/api.js file and add the following code:

import axios from 'axios';

const API_KEY = 'YOUR_API_KEY';
const API_URL = 'https://api.openweathermap.org/data/2.5/weather';

export const fetchWeather = async (latitude, longitude) => {
  try {
    const url = `${API_URL}?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
    const response = await axios.get(url);
    return response.data;
  } catch (error) {
    throw new Error('Could not fetch weather data');
  }
};

Replace 'YOUR_API_KEY' with the API key you obtained from OpenWeatherMap.

This code sets up the base URL for the OpenWeatherMap API and provides a fetchWeather function that takes latitude and longitude as parameters. It makes an HTTP GET request to the API and returns the response data.

Step 6: Retrieve the User’s Location

In the src directory, create a new file called Location.js. This file will contain a function to retrieve the user’s location.

Open the src/Location.js file and add the following code:

import Geolocation from 'react-native-geolocation-service';

export const getUserLocation = () => {
  return new Promise((resolve, reject) => {
    Geolocation.getCurrentPosition(
      position => {
        const { latitude, longitude } = position.coords;
        resolve({ latitude, longitude });
      },
      error => {
        reject(error);
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  });
};

This code uses the getCurrentPosition function from the react-native-geolocation-service library to retrieve the user’s current position. It returns a promise that resolves with the latitude and longitude.

Step 7: Create the Weather Component

In the src directory, create a new file called Weather.js. This file will contain the main component that displays the weather information.

Open the src/Weather.js file and add the following code:

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { getUserLocation } from './Location';
import { fetchWeather } from './api';

const Weather = () => {
  const [weatherData, setWeatherData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchWeatherData = async () => {
      try {
        const { latitude, longitude } = await getUserLocation();
        const data = await fetchWeather(latitude, longitude);
        setWeatherData(data);
        setLoading(false);
      } catch (error) {
        console.error(error);
      }
    };

    fetchWeatherData();
  }, []);

  if (loading) {
    return (
      <View>
        <Text>Loading...</Text>
      </View>
    );
  }

  if (!weatherData) {
    return (
      <View>
        <Text>Could not fetch weather data</Text>
      </View>
    );
  }

  const { main, description } = weatherData.weather[0];

  return (
    <View>
      <Text>Main: {main}</Text>
      <Text>Description: {description}</Text>
    </View>
  );
};

export default Weather;

This code sets up a functional component called Weather that initializes the state variables weatherData and loading using the useState hook.

In the useEffect hook, we fetch the user’s location and then use that information to fetch the weather data using the fetchWeather function from api.js. We update the state variables accordingly.

The component then renders different views based on the loading and weatherData variables. While the data is being fetched, it shows a loading message. If the data couldn’t be fetched, it shows an error message. Otherwise, it displays the main weather condition and description.

Step 8: Render the Weather Component

Open the App.js file in the project directory and replace the existing code with the following:

import React from 'react';
import { View, StyleSheet } from 'react-native';
import Weather from './src/Weather';

const App = () => {
  return (
    <View style={styles.container}>
      <Weather />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default App;

This code sets up the main app component (App) and renders the Weather component inside a View component.

We also define a simple style using the StyleSheet.create function to center the content within the View.

Step 9: Run the App

To run the app on your Android or iOS device, make sure you have the emulator or device connected to your computer.

In the project directory, run the following command:

npx react-native run-android

or

npx react-native run-ios

This will compile the app and install it on your device. You should now see the weather information displayed on the screen.

Congratulations! You have successfully created a weather app with React Native.

Conclusion

In this tutorial, you learned how to create a weather app with React Native. You set up a new React Native project, obtained an API key from OpenWeatherMap, retrieved the user’s location, made API requests to fetch weather data, and displayed the information in a component. You also learned how to handle loading and error states.

Feel free to enhance the app by adding more features such as displaying more weather information, implementing location search, or customizing the UI. Happy coding!

Related Post