How to Build a Weather App in React

How to Build a Weather App in React

React is widely used for web development and has a large community of developers contributing to its growth. React allows developers to build complex and interactive applications with ease.

In this tutorial, you will learn how to build a weather app in React. The app will fetch data from an API and display the weather for a given location.

Before you begin, it’s important to note that you will be using the OpenWeatherMap API to fetch weather data. This API requires an API key, which can be obtained by signing up on their website.

How to Build a Weather App in React

Use the following steps to make/build weather app in react js applications; as follows:

  • Step 1 – Create React App
  • Step 2 – Install Bootstrap and Icons
  • Step 3 – Get API KEY From WeatherMap
  • Step 4 – Create a Weather Component
  • Step 5 – Use the Weather Component
  • Step 6 – Style the Weather App
  • Step 7 – Run React Weather App

Step 1 – Create React App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Bootstrap and Icons

In this step, execute the following command to install boostrap 4 library into your react app:

npm install bootstrap --save
npm i bootstrap-icons

Then import bootstrap library and icons in app.js file:

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "../node_modules/bootstrap-icons/font/bootstrap-icons.css";

Step 3 – Get API KEY From WeatherMap

Use the following steps to get an API key.

  • Visit this url :- OpenWeatherMap API
  • Create a new account.
  • Visit Profile>My API Key and copy API Key or create a new one
  • Visit API>Current Weather Data>API Doc and get code of API Call

Once you have your API key, create a new file called .env in the root directory of your app and add the following line:

REACT_APP_API_KEY=<your API key>

Make sure to replace <your API key> with your actual API key.

Step 4 – Create a Weather Component

Now that you have all of our dependencies installed and our API key set up, let’s create a new component called Weather. This component will be responsible for displaying the weather data for a specific location.

In your src directory, create a new file called Weather.js. In this file, add the following code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import moment from 'moment';
import { WiDaySunny, WiRain, WiSnow, WiCloudy, WiDayCloudy, WiFog } from 'react-icons/wi';

const Weather = ({ location }) => {
  const [weatherData, setWeatherData] = useState(null);

  useEffect(() => {
    const fetchWeatherData = async () => {
      const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${process.env.REACT_APP_API_KEY}&units=metric`);
      setWeatherData(response.data);
    };
    fetchWeatherData();
  }, [location]);

  if (!weatherData) {
    return null;
  }

  const temperature = Math.round(weatherData.main.temp);
  const description = weatherData.weather[0].description;
  const iconCode = weatherData.weather[0].icon;
  const icon = getIcon(iconCode);
  const date = moment().format('dddd, MMMM Do YYYY');

  return (
    <div className="weather">
      <div className="weather-header">
        <h2 className="weather-location">{location}</h2>
        <p className="weather-date">{date}</p>
      </div>
      <div className="weather-body">
        <div className="weather-temperature">{temperature}°C</div>
                <div className="weather-icon">{icon}</div>
                <div className="weather-description">{description}</div>
                </div>
                </div>
                );
                };

                const getIcon = (iconCode) => {
                switch (iconCode) {
                case '01d':
                return <WiDaySunny />;
                case '01n':
                return <WiDaySunny />;
                case '02d':
                return <WiDayCloudy />;
                case '02n':
                return <WiDayCloudy />;
                case '03d':
                case '03n':
                return <WiCloudy />;
                case '04d':
                case '04n':
                return <WiCloudy />;
                case '09d':
                case '09n':
                return <WiRain />;
                case '10d':
                case '10n':
                return <WiRain />;
                case '11d':
                case '11n':
                return <WiThunderstorm />;
                case '13d':
                case '13n':
                return <WiSnow />;
                case '50d':
                case '50n':
                return <WiFog />;
                default:
                return null;
                }
                };

export default Weather;

Let’s break down what’s happening in this component. First, you import the necessary dependencies, including React, useState, useEffect, axios, moment, and react-icons. And also import the weather icons that will use later on.

The Weather component takes a location prop, which specifies the location that you want to get the weather data for. Inside the component, To define a state variable called weatherData using the useState hook. This variable will hold the weather data that get from the OpenWeatherMap API.

In the useEffect hook, you make an API request to OpenWeatherMap to get the weather data for the specified location. Then use the axios library to make the request and set the weatherData state variable with the response data.

You then check if weatherData is null. If it is, return null to prevent the component from rendering before you have the weather data. If weatherData is not null, and extract the necessary data from the response and format the date using the moment library.

Finally, you return the weather data in a styled HTML structure. Then use the getIcon function to display the appropriate weather icon based on the iconCode that get from the API response.

Step 5 – Use the Weather Component

Now that you have created our Weather component, let’s use it in our app. In the App.js file, replace the existing code with the following:

import React from 'react';
import './App.css';
import Weather from './Weather';

function App() {
return (
<div className="App">
<Weather location="New York" />
<Weather location="London" />
<Weather location="Sydney" />
</div>
);
}

export default App;

In this code, you import the Weather component and use it three times, passing in different locations as props. You can replace these locations with the locations that you want to display weather data for.

Step 6 – Style the Weather App

To make our weather app look good, you need to add some styles. In the App.css file, add the following code:

.App {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.weather {
display: flex;
flexdirection: column;
justify-content: center;
align-items: center;
margin: 20px;
padding: 20px;
border-radius: 10px;
background-color: #fff;
box-shadow: 0px 3px 10px rgba(0, 0, 0, 0.1);
width: 300px;
}

.weather-location {
font-size: 24px;
font-weight: bold;
margin-bottom: 10px;
}

.weather-date {
font-size: 16px;
margin-bottom: 10px;
}

.weather-temperature {
font-size: 64px;
font-weight: bold;
margin-bottom: 10px;
}

.weather-icon {
font-size: 48px;
margin-bottom: 10px;
}

.weather-description {
font-size: 20px;
}

@media screen and (max-width: 600px) {
.App {
flex-direction: column;
}

.weather {
margin: 20px 0;
width: 100%;
}
}

In this code, to define styles for the App component and the weather div. you also define styles for the different elements inside the weather div.

Step 7 – Run React Weather App

To test our weather app, you can run the following command in the terminal:

npm start

This will start the app in development mode and open the following URL in your web browser window. You should see the weather data for the locations that you specified in the App.js file.

http://localhost:3000/

Conclusion

In this tutorial, you have learned the process of building a weather app in React using the OpenWeatherMap API. By following the steps outlined in this guide, you should now have a working weather app that displays weather data for different locations.

You started by creating a new React app and setting up the API key and necessary dependencies. Next, you created a new Weather component and fetched weather data from the OpenWeatherMap API using the fetch() method. You then used the Weather component in the App.js file and passed in the weather data as props.

Finally, you styled the weather app using CSS and tested it in the browser. With this knowledge, you can now add additional features to your weather app, such as user input for location or a five-day forecast.

Building a weather app in React can be a great way to improve your skills and learn new techniques. We hope that this tutorial has been helpful in guiding you through the process of building a weather app in React.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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