How to build a Weather App with React & Tailwind CSS

Amrin - Feb 11 '23 - - Dev Community

Hello everyone,
today we’ll build a weather app with React and Tailwind CSS. We will use the Openweather API for the weather data.

If you prefer video check it out:

Prerequisite:

To follow along in the article, you’’ll need to know:

  1. The fundamentals of JavaScript
  2. The fundamentals of CSS & tailwind CSS
  3. An Openweather account

What you’ll learn:

At the end of the article you’ll learn how to make API call with fetch api. And how to render the data on the screen you got from the API

Generating API key:

  1. Go to the Openweather website and login
  2. Then click on your name
  3. then go to “My API Keys” and generate a key.

Installation:

We are going to build this project with React and Tailwind CSS.
In order to follow along, you will have to setup a basic React and Tailwind project.

You can do that by following these steps:

Create your project:

npx create-react-app my-project
cd my-project
Enter fullscreen mode Exit fullscreen mode

Install and initialize Tailwind:

npm install -D tailwindcss
npx tailwindcss init
Enter fullscreen mode Exit fullscreen mode

Configure template path:

Add this to your tailwind.config.js file

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

Add the tailwind directives:

Add these to your index.css file

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Project setup is complete. Let’s get into building the project.

Initial setup:

Import the css file and useState and useEffect hooks in the app.js file.

And initialize the states using the useState hook.

import "./App.css";
import { useState, useEffect } from "react";

function App() {
  const [city, setCity] = useState("New York");
  const [weather, setWeather] = useState();

  return (
    <div className="app flex flex-col items-center">
        Hello world!
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Custom CSS

Our project has a full page background. So we’ll have to add that with custom css. The image is included in the projects file.

.app {
    background: url("./bg.png") center no-repeat;
    background-size: cover;
    height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Fetching the weather Data:

We will fetch the weather using the fetch API. We will create a function that will fetch the weather and store it on the state.

const fetchWeather = () => {
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY_HERE&units=metric`
    )
      .then((res) => res.json())
      .then((data) => setWeather(data))
      .catch((error) => console.log(error.message));
  };
Enter fullscreen mode Exit fullscreen mode

As you can see the url takes a city name to fetch the weather. So, we’ll have to get the city from the user.

Let’s create a form and store the city name in the state we created earlier.

<h1 className="py-4 text-5xl text-white font-serif">Search Weather</h1>
 <div className="form">
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            placeholder="Enter city name"
            className="px-4 py-3"
            value={city}
            onChange={(e) => setCity(e.target.value)}
          />
          <button type="submit" className="px-4 py-3 bg-purple-500 text-white">
            Search
          </button>
        </form>
  </div>
Enter fullscreen mode Exit fullscreen mode

As you can see above we’ve also attached a handleSubmit function to the onSubmit event. It’ll throw an error right now.
Let’s go ahead and declare that.

const handleSubmit = (e) => {
    e.preventDefault();
    fetchWeather();
  };
Enter fullscreen mode Exit fullscreen mode

This is a simple function, All it’ll do is call the fetchWeather function and prevent the page from loading when the form is submitted.

Display the weather Data:

Now that we got the weather data let’s display it on the screen.

To display the weather we’ll first check if it exits then we will render the data.

add this after the form.

{weather && (
        <div className="card bg-purple-500 text-white w-[220px] h-[350px] flex flex-col justify-center items-center mt-10">
          <h4 className="text-2xl">{weather.name}</h4>
          <img
            src={`http://openweathermap.org/img/w/${weather.weather[0].icon}.png`}
            alt=""
            className="w-[150px]"
          />
          <h2 className="text-5xl font-bold mb-2">{weather.main.temp}&deg;</h2>
          <p>{weather.weather[0].main}</p>
        </div>
      )}
Enter fullscreen mode Exit fullscreen mode

Conclusion:

In this article we’ve built a weather app with React and Tailwind CSS. You learned how to make API call with fetch API.
Hope it was helpful.

If you want to read more articles like this follow me.

Connect with me:

Twitter: https://twitter.com/CoderAmrin
YouTube: https://www.youtube.com/@coderamrin/

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .