In this tutorial, you’ll discover how to construct a weather application using React. This application will retrieve data from an API and exhibit the weather conditions for a specified location.
Prior to diving in, it’s crucial to understand that you’ll utilize the OpenWeatherMap API to fetch weather data. Access to this API necessitates an API key, which you can acquire by registering on their website.
Step 1 – Create React App
In this step, open your terminal and execute the following command to create a new React app:
npx create-react-app my-weather-app
To run the React app, execute the following command on your terminal and check out your React app on this URL: localhost:3000
npm start
Step 2 – Installing Bootstrap and Icons
Execute the following command to install the Bootstrap 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
Follow these steps to obtain an API key:
- Visit the following URL: OpenWeatherMap API.
- Create a new account if you haven’t already.
- Go to your profile settings and navigate to “My API Key”. Copy your API key or generate a new one if needed.
- Proceed to the API documentation for “Current Weather Data” to understand how to make API calls and get the necessary code.
Once you have obtained your API key, follow these steps:
- Create a new file named
.env
in the root directory of your application. - Add the following line to the
.env
file: - Make sure to replace
<your API key>
with your actual API key.
REACT_APP_API_KEY=<your API key>
Step 4 – Creating a Weather Component
Now that all dependencies are installed and the API key is set up, let’s create a new component called Weather. This component will handle the display of weather data for a particular location.
- In your
src
directory, create a new file namedWeather.js
. - Add the following code to the
Weather.js
file:
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;
This code is a React component called Weather
that fetches weather data from the OpenWeatherMap API based on a provided location. Here’s a breakdown of how it works:
-
Imports: The code imports necessary modules and components such as
React
,useState
,useEffect
from React,axios
for making HTTP requests,moment
for formatting dates, and weather icons fromreact-icons/wi
. -
Weather Component: The
Weather
component is defined as a functional component that takes alocation
prop. -
useState: It uses the
useState
hook to manage the state ofweatherData
, which will hold the fetched weather data. -
useEffect: It utilizes the
useEffect
hook to perform side effects, such as fetching data, after the component has mounted or when thelocation
prop changes. It fetches weather data from the OpenWeatherMap API using Axios. -
Render: If
weatherData
is not yet available (null), the component returns null, indicating that it’s still loading. -
Data Extraction: Once the weather data is fetched, it extracts necessary information like temperature, description, icon code, and formats the current date using Moment.js.
-
Icon Mapping: The
getIcon
function takes an icon code as input and returns the corresponding weather icon component fromreact-icons/wi
. -
Rendering Weather: The component then renders the weather information including location, date, temperature, weather icon, and description.
-
Icon Rendering: Depending on the weather condition (as indicated by the icon code), the appropriate weather icon component is rendered using the
getIcon
function. -
Export: Finally, the
Weather
component is exported as the default export of this module.
Step 5 – Utilizing the Weather Component
Now that you’ve created the Weather component, let’s integrate it into our app. Follow these steps:
- 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;
This code is the main entry point of a React application. Let’s break it down:
-
Imports: The code imports the
React
library and theApp.css
file for styling, as well as theWeather
component from the local fileWeather.js
. -
App Component: The
App
function is defined as a functional component. This is the root component of the application. -
Return JSX: Inside the
App
component, there’s a JSX return statement. It contains a<div>
element with a class name of “App”. Inside this<div>
, threeWeather
components are rendered with different locations: New York, London, and Sydney. -
Export: The
App
component is exported as the default export of this module, making it accessible to other parts of the application.
Overall, this code sets up the main structure of the React application, rendering the Weather
component three times with different locations. Each Weather
component will fetch and display weather information for its respective location.
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 for which you want to display weather data.
Step 6 – Styling the Weather App
To enhance the appearance of our weather app, let’s add some styles. Follow these steps:
- 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%;
}
}
This CSS code provides styling for the React application. Let’s break it down:
-
General Styles:
.App
: This class sets up the main container for the entire application. It uses Flexbox to center its children both horizontally and vertically (justify-content: center; align-items: center;
). It also sets the height of the container to 100% of the viewport height (height: 100vh;
)..weather
: This class styles the weather component. It sets it as a flex container with column direction (flex-direction: column;
), centers its children both horizontally and vertically, adds margin and padding, sets border radius, background color, and box shadow to give it a card-like appearance. It also sets a fixed width of 300px.
-
Weather Component Styles:
.weather-location
: Styles the location name with a larger font size, bold weight, and adds some bottom margin..weather-date
: Styles the date with a smaller font size and adds bottom margin..weather-temperature
: Styles the temperature with a very large font size, bold weight, and adds bottom margin..weather-icon
: Styles the weather icon with a large font size and adds bottom margin..weather-description
: Styles the weather description with a moderate font size.
-
Media Query:
- This media query targets screens with a maximum width of 600px.
- It adjusts the layout of the
.App
class to have a column direction for smaller screens (flex-direction: column;
). - It adjusts the
.weather
class to have full width and removes the left and right margins to accommodate smaller screens (margin: 20px 0; width: 100%;
).
Overall, this CSS code provides responsive styling for the application, ensuring that it looks good both on larger screens and on smaller screens such as mobile devices.
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 at http://localhost:3000/
Conclusion
In this tutorial, you’ve gone through the process of creating a weather app in React utilizing the OpenWeatherMap API. By following the steps outlined here, you should now have a functional weather app capable of displaying weather data for various locations.
You began by setting up a new React app and configuring the API key and dependencies required. Then, you developed a Weather component responsible for fetching weather data from the OpenWeatherMap API using the fetch() method. This component was integrated into the App.js file, where weather data was passed as props.
Lastly, you styled the weather app using CSS to enhance its appearance and tested it in the browser. Armed with this knowledge, you can expand the capabilities of your weather app by incorporating features such as user input for location or a five-day forecast.
Creating a weather app in React offers an excellent opportunity to enhance your skills and explore new techniques. We trust that this tutorial has served as a valuable guide in your journey to build a weather app in React.