Categories
React Projects

Create a Weather App with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

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

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app weather-app

with NPM to create our React project.

Create the Weather App

To create the weather app, we write:

import React, { useState } from "react";
const APIKEY = "your-key";

export default function App() {
  const [city, setCity] = useState("");
  const [result, setResult] = useState({});

  const getWeather = async (e) => {
    e.preventDefault();
    if (!city) {
      return;
    }
    const res = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKEY}`
    );
    const { main } = await res.json();
    setResult(main);
  };

  return (
    <div>
      <form onSubmit={getWeather}>
        <div>
          <label>city</label>
          <input value={city} onChange={(e) => setCity(e.target.value)} />
        </div>
        <button type="submit">get weather</button>
      </form>
      {result && (
        <div>
          <p>feels like: {result.feels_like}</p>
          <p>humidity: {result.humidity}</p>
          <p>pressure: {result.pressure}</p>
          <p>temperature: {result.temp}</p>
          <p>high: {result.temp_max}</p>
          <p>low: {result.temp_min}</p>
        </div>
      )}
    </div>
  );
}

We define the APIKEY variable set to the API key for the OpenWeather API.

The API key can be obtained for free from https://home.openweathermap.org/api_keys.

Next, we define the city state which we use to bind the inputted value of the city field to it.

The result field has the weather results.

Next, we define the getWeather function to get the weather data by city .

Inside it, we call e.preventDefault() to let us do client-side form submission.

Then we check if city is set.

If it’s set, then we make an API request to the Open Weather API with fetch .

And we call setResult to set the result.

Below that, we create a form with the onSubmit prop set to getWeather so that getWeather is called when we click on the get weather button.

Inside the form, we have an input set to a value and onChange props.

onChange is set to a function to set the city state’s value.

e.target.value has the inputted value.

Below the form, we show the result properties top the user.

Conclusion

We can create a weather app easily with React and JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *