How to create a weather app with React Native?

(Source code is at https://github.com/jauyeunggithub/rook-hotel-answers/blob/master/q5.txt)

Sometimes, we want to create a weather app with React Native.

In this article, we’ll look at how to create a weather app with React Native.

How to create a weather app with React Native?

To create a weather app with React Native, we can make requests to a weather API to get weather data when someone enters a query in the search box.

For instance, we write:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import { useState, useEffect } from 'react';
import { Card } from 'react-native-paper';
import { TextInput, Button } from "react-native";


export default function App() {
  const [data, setData] = useState({});
  const [query, setQuery] = useState('');

  const getWeather = async () => {
    const res = await fetch(`https://www.metaweather.com/api/location/search/?query=${query}`);
    const [{woeid}] = await res.json();
    const resWeather = await fetch(`https://www.metaweather.com/api/location/${woeid}`);
    const d = await resWeather.json();
    setData(d);
  };

  return (
    <View style={styles.container}>
      <TextInput value={query} onChange={e => setQuery(e.target.value)} placeholder='Type Location to Search' />
      <Button title='Search' onPress={getWeather} />      
      <Card>
        {JSON.stringify(data)}
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

We define the data state to store the weather data.

And we have the query state to store the query input value.

Next, we define the getWeather function to make GET requests to the MetaWeather API with fetch.

And we call setData to set data to the result of the 2nd request.

Then we render a Virew with a TextInput to let users enter a query to search for weather data.

We have a Button which calls getWeather to make requests for the weather data according to the query value.

Then we display the retrieved data in a Card.

We add some styles to the View to center the content with justifyContent set to center and set a backgroundColor.

Conclusion

To create a weather app with React Native, we can make requests to a weather API to get weather data when someone enters a query in the search box.