DEV Community

Cover image for React Weather App Made Easy!
nickwarren47
nickwarren47

Posted on

React Weather App Made Easy!

When I was developing one of my travel apps, I wanted to give the user the ability to see the weather conditions at any dive site. After much thought, I decided to dive in (SCUBA dive pun intended). I will show you how to quickly develop a basic React weather app to add to any app you are making.

Getting Started With The API
When building an app like this, the best place to start is to find an API that will suite your needs. For this app, I wanted to find an API that was free and didn't have too many restrictions on the amount of fetches you could make to the API. I elected to use this API: OpenWeather. In OpenWeather's site, I signed up for free and created an account. After that was done, I went to their section titled "API" and then selected the "Current Weather Data."

Image description

In the "Current Weather Data" section, I then selected "Get API Key" from the "Free" data column. Note: the API key may take 24 hours to become activated, so be sure to plan accordingly if you need to deploy this app quickly.

Image description

After receiving your API key, now you will need to take a look at the API documentation for using the key in conjunction with the URL. I want to note that the code I am displaying is what I used to render the weather feature in my app. I highly recommend reading the API documentation as this may have changed after writing this blog. Also, for obvious reasons, I will be excluding the API key I used from this article. To retrieve data from the API, you will need to make some additions to the URL:
https://api.openweathermap.org/data/2.5/weather?q=${location}&units=<add unit type here>&appid=<add API key here>
You will notice in the code snippet above that you will need to add the unit type (either metric or imperial) and you will need to supply your API key. You will notice the "${location}", don't worry about this right now, we will come back to it in a little bit.

Adding Your Code To React
Now that you have everything you need from the API, it's time to add some code to VS. To start, if you haven't already, I would recommend creating a React app using the command:
npx create-react-app my-project
After first creating your app, then you will need to run:
npm install axios
After running this command, you will then have axios available to you for your app. Now, create a file in your project directory for the weather app (for mine, I just called it "Weather.js"). For simplicity, we will also just call our page "Weather.js". Now, on the "Weather.js" page, we will need to type in the following:

import React, { useState } from 'react'
import axios from 'axios'

function Weather(){
}

return(
<div>
</div>
)

export default Weather;
Enter fullscreen mode Exit fullscreen mode

Now, let's set up our state variables and the weather API URL as constants:

import React, { useState } from 'react'
import axios from 'axios'

function Weather(){
    const [data,setData] = useState({})
    const [location, setLocation] = useState('')

    const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${location}&units=imperial&appid=*******************`
}

return(
<div>
</div>
)

export default Weather;
Enter fullscreen mode Exit fullscreen mode

Again, you will notice in the WeatherUrl const that I obscured the API key (be sure to copy and paste your own API key in after the "appid=") and I set units to "imperial". If you do not specify the units, the API will default to Kelvin temperature values. Also, note that I set the "data" state to an empty object and the location to an empty string. The data we will receive from the API will be in an object and the location will allow us to search by location when we enter a string data type.

In the next step, we will both fetch our data and set up our location search capabilities (we will call it "searchWeatherLocation"):

import React, { useState } from 'react'
import axios from 'axios'

function Weather(){
    const [data,setData] = useState({})
    const [location, setLocation] = useState('')

    const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${location}&units=imperial&appid=*******************`

    const searchWeatherLocation = (event) => {
        if (event.key === 'Enter'){
            axios.get(weatherUrl).then((response) => {
                setData(response.data)
                console.log(response.data)
            })
            setLocation('')
        }
    }
}

return(
<div>
</div>
)

export default Weather;
Enter fullscreen mode Exit fullscreen mode

This is why I added the "${location}" to the API to allow for the location to change depending on the user's inputs. Also, I highly recommend adding in the console.log(response.data) to test if the data is being received from the API. This will allow you to do 2 things:

  1. Make sure that you are getting a connection to the API and that your API key, URL, and code are correct.
  2. It allows you to see what data the API will give you and you can determine what weather data you want to display (in my case, I displayed the temp, feels like temp, humidity, weather description, and wind speed).

Time To Display Data
Once you are receiving the data from the API, you can now begin to display the results. For my app, I used Tailwind CSS as my UI kit framework and I will be showing the styling I used to display the data with Tailwind styling.

We have ignored the "return ()" section of our code but now we can add the following code:

return(
<div>
   <div className="flex items-center justify-center">
      <input 
         value={location}
         className=" bg-transparent rounded-lg border-white text-white font-bold text-2xl border-8 mb-20"
         onChange={event => setLocation(event.target.value)}
         onKeyPress={searchWeatherLocation}  
         placeholder="Enter City Name Here..."
         type="text"/>
    </div>
 <div className='flex items-center justify-center my-36'>
    <div className="top">
       <div className="temp">
          <h1 className="text-6xl text-white font-bold">Current Weather In:</h1>
       </div>
       <br/>
       <div className="location text-center">
          <p className="text-4xl text-white font-bold">{data.name </p>
       </div>
       <div className="temp text-center">
           {data.main ? <h1 className="text-8xl text-white font-bold">{data.main.temp.toFixed()}°F</h1> : null}
       </div>
       <div className="description text-center">
         {data.weather ?  <p className="text-3xl text-white font-bold">{data.weather[0].description}</p> : null}
       </div>
       <br/>
       <div className="flex items-center justify-center pl-11">
          <div className="feels text-center">
              {data.main ? <p className="text-3xl text-white font-bold pr-9">{data.main.feels_like.toFixed()}°F</p> : null}
              <p className="text-3xl text-white font-bold pr-9"> Feels Like</p>
  </div>
</div> 
</div>
)
Enter fullscreen mode Exit fullscreen mode

Now, this may look like a jumble of code but let's break it down. The first part of the code is establishing the ability to search based on location with some Tailwind CSS styling mixed in (the "className" are used for Tailwind styling):

   <div className="flex items-center justify-center">
      <input 
         value={location}
         className=" bg-transparent rounded-lg border-white text-white font-bold text-2xl border-8 mb-20"
         onChange={event => setLocation(event.target.value)}
         onKeyPress={searchWeatherLocation}  
         placeholder="Enter City Name Here..."
         type="text"/>
    </div>
Enter fullscreen mode Exit fullscreen mode

In the code above, the "onChange" is setting the "setLocation" setter function in our state to the input value and "onKeyPress" is telling the code to go run our "searchWeatherLocation" function.

As for the styling, we can also break that down too...

       <div className="temp">
          <h1 className="text-6xl text-white font-bold">Current Weather In:</h1>
       </div>
Enter fullscreen mode Exit fullscreen mode

This section is just adding the text to say "Current Weather In:"

       <div className="location text-center">
          <p className="text-4xl text-white font-bold">{data.name </p>
       </div>
Enter fullscreen mode Exit fullscreen mode

This section of code is grabbing the location name from the data and displaying the name.

       <div className="temp text-center">
           {data.main ? <h1 className="text-8xl text-white font-bold">{data.main.temp.toFixed()}°F</h1> : null}
       </div>
Enter fullscreen mode Exit fullscreen mode

This section of code is grabbing the "main temp" from our data which we had to drill down into to let React know we want this specific value. I also added a ternary expression so that it will either display the temp if it is present or not display anything. This will be important for when our app is not in use and we haven't given it a location yet.

<div className="description text-center">
         {data.weather ?  <p className="text-3xl text-white font-bold">{data.weather[0].description}</p> : null}
       </div>
       <br/>
       <div className="flex items-center justify-center pl-11">
          <div className="feels text-center">
              {data.main ? <p className="text-3xl text-white font-bold pr-9">{data.main.feels_like.toFixed()}°F</p> : null}
              <p className="text-3xl text-white font-bold pr-9"> Feels Like</p>
  </div>
Enter fullscreen mode Exit fullscreen mode

I lumped both of these sections of code together because they follow the same trend as the one I talked about above this code. Again, we are telling React what section of the data by clarifying that we want {data.main.feels_like} for example. This will depend on what data you want but for this blog, I just grabbed the location name, temp, feels like temp, humidity, description, and wind speed. There are many other data points that are provided by OpenWeather for you to use. For the other data points like humidity and wind speed, I followed the same code pattern as the code shown above.

The Finished Product
Congratulations, you now have a fully functional React Weather app!! For my app, I Tailwind CSS techniques to make a transparent background for displaying the weather.

Image description

Conclusion and Things to Look Out For
One thing I want to note is that when you are using an API key, it is very important to hide it if you are using an API that contains your personal info or you have to pay for. It is very important that you look into properly hiding your API key.

Top comments (0)