How to build a Weather App with React & Tailwind CSS
Tags: webdev, react, beginners, tutorial
Published: 2023-02-11 17:30:11

Hello everyone, 
today we’ll build a weather app with React and Tailwind CSS.  We will use the [Openweather](https://openweathermap.org/) API for the weather data. 

**If you prefer video check it out:**
{% youtube uegqhdvU0lM  %}

### 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](https://openweathermap.org/) 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](https://openweathermap.org/api) 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:**

```jsx
npx create-react-app my-project
cd my-project
```

**Install and initialize Tailwind:**

```jsx
npm install -D tailwindcss
npx tailwindcss init
```

**Configure template path**:

Add this to your tailwind.config.js file

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

**Add the tailwind directives:**

Add these to your index.css file

```jsx
@tailwind base;
@tailwind components;
@tailwind utilities;
```

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.

```jsx
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;
```

### 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. 

```jsx
.app {
    background: url("./bg.png") center no-repeat;
    background-size: cover;
    height: 100vh;
}
```

### 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. 

```jsx
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));
  };
```

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. 

```jsx
<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>
```

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.

```jsx
const handleSubmit = (e) => {
    e.preventDefault();
    fetchWeather();
  };
```

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.

```jsx
{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>
      )}
```

### 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/