Share
Explore

Lab Learning Workbook: Building a Weather App with React.js and OpenWeatherMap API

Lab Checklist:

Signup for
___ OpenWeather API key
___ CodePen.io
Start by setting up a Node Project on Codepen.io
Next lab: We will integrate mashups with Google Maps -> mashup a weather canvas with Weather display pins

Learning Outcomes:

Network programming using the Axios library


info

To build a weather application in React.js that fetches data from the OpenWeatherMap API, you will need to install and use several npm packages.

Here are some of the key packages that you might need:

React: This is the core library for building user interfaces in JavaScript. It allows you to create reusable UI components and manage their state
.
Installation: npm install react
Axios: This is a promise-based HTTP client for making HTTP requests from the browser. It can be used to make the HTTP call to the OpenWeatherMap API
.
Installation: npm install axios
react-http-request: This is a React component that exposes network request functionality. It can be used to perform a network request and parse the response
.
Installation: npm install --save react-http-request
http-react: This is a React hooks library for data fetching. It's built on top of the native Fetch API and can be used to make the HTTP request to an API server, in this case: the OpenWeatherMap API
.
Installation: npm install --save http-react
Formik: This is a popular open-source library for managing forms in React applications. It can be used to create the input form for specifying the city
.
Installation: npm install formik
Remember to import these packages in your React.js files using the import statement before using them.
For example, to use Axios, you would add the line import axios from 'axios'; at the top of your file
.
Please note that the exact packages you need may vary depending on the specific requirements of your application and your personal preferences.
Always refer to the official documentation of each package for the most accurate and up-to-date information.

Welcome to the Weather App Lab!


Today, we will be building a simple weather application using React.js and the OpenWeatherMap API. This lab is designed to be completed within a 2-hour class duration. {Quite similar to the expectations of Lab Test 2}.

## Prerequisites

Before we begin, you will need to sign up for a free account with OpenWeatherMap to get an API key. You can get an API key by following this link: [14].

## Benefits of Using a Cloud-Based IDE

Cloud-based IDEs offer several advantages over traditional local development environments. They offer hassle-free configuration, as the development environment runs fully on a browser, eliminating the need for complex setup processes.
They also allow for easy collaboration and are accessible from any device that supports a modern web browser. For this lab, we will be using CodePen, a free cloud-based IDE[3][11].

## Step-by-Step Guide

### Step 1: Setting Up the Project on CodePen.io
1. Navigate to https://codepen.io/ and sign up for a free account if you don't have one. 2. Click on the "Create" button at the top right corner and select "New Pen". 3. You should now see three sections: HTML, CSS, and JS. We will be writing our code in these sections.
### Step 2: Writing the HTML
In the HTML section, write the following code:
```html <div id="app"></div> ```
This is the root element where our React application will be mounted[12].

### Step 3: Adding React Libraries

In the JS section, click on the settings icon (gear icon) and under "JavaScript Preprocessor", select "Babel". This will allow us to write modern JavaScript that is compatible with older browsers.
Next, under "Add External Scripts/Pens", add the following two URLs to include the React and ReactDOM libraries:
- https://unpkg.com/react@17/umd/react.development.js - https://unpkg.com/react-dom@17/umd/react-dom.development.js

### Step 4: Writing the React Component

In the JS section, write the following code:

```javascript class WeatherApp extends React.Component { render() { return ( <div> <h1>Hello, world!</h1> </div> ); } }
ReactDOM.render(<WeatherApp />, document.getElementById('app')); ```
This code creates a simple React component that renders "Hello, world!" to the screen[4].

### Step 5: Fetching Data from the OpenWeatherMap API

We will now modify our `WeatherApp` component to fetch data from the OpenWeatherMap API. Replace the existing `WeatherApp` code with the following:

```javascript class WeatherApp extends React.Component { constructor(props) { super(props); this.state = { weatherData: null }; }
componentDidMount() { fetch('https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY') .then(response => response.json()) .then(data => this.setState({ weatherData: data })); }
render() { const { weatherData } = this.state;
if (!weatherData) return <div>Loading...</div>;
return ( <div> <h1>Weather in {weatherData.name}</h1> <h2>{Math.round(weatherData.main.temp - 273.15)}°C</h2> <p>{weatherData.weather[0].description}</p> </div> ); } }
ReactDOM.render(<WeatherApp />, document.getElementById('app')); ```
Remember to replace `YOUR_API_KEY` with your actual API key from OpenWeatherMap[14].

megaphone

To allow the user to specify the city to pull the weather from, we can add an input form to our React.js application. This form will give the user the option to enter a city name. When the user submits the form, the application will make an HTTP call to the OpenWeatherMap API to retrieve the weather data for the specified city. Here's how you can implement this:

### Step 6: Adding User Input
First, we need to add an input form to our `WeatherApp` component. Modify the `render` method as follows:
```javascript render() { const { weatherData } = this.state;
if (!weatherData) return <div>Loading...</div>;
return ( <div> <form onSubmit={this.handleSubmit}> <input type="text" value={this.state.city} onChange={this.handleInputChange} /> <input type="submit" value="Get Weather" /> </form> <h1>Weather in {weatherData.name}</h1> <h2>{Math.round(weatherData.main.temp - 273.15)}°C</h2> <p>{weatherData.weather[0].description}</p> </div> ); } ```
Next, we need to add the `handleInputChange` and `handleSubmit` methods to our `WeatherApp` component to handle the form submission:
```javascript handleInputChange(event) { this.setState({ city: event.target.value }); }
handleSubmit(event) { event.preventDefault(); this.fetchWeatherData(this.state.city); } ```
Finally, we need to modify the `componentDidMount` method to `fetchWeatherData` method and call this method in `handleSubmit`:
```javascript fetchWeatherData(city) { fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY`) .then(response => response.json()) .then(data => this.setState({ weatherData: data })); } ```
Remember to replace `YOUR_API_KEY` with your actual API key from OpenWeatherMap[5].
Now, when the user enters a city name into the input form and clicks the "Get Weather" button, the application will fetch and display the weather data for the specified city.
Citations: [1] https://youtube.com/watch?v=Reny0cTTv24 [2] https://www.htmlhints.com/article/how-to-create-weather-app-using-reactjs-with-current-location-search-city/93 [3] https://www.freecodecamp.org/news/learn-react-by-building-a-weather-app/ [4] https://github.com/topics/react-weather-app [5] https://rapidapi.com/blog/weather-app-react/ [6] https://youtube.com/watch?v=xBqEWbirtvA


In the provided lab, the output is presented on the app screen by rendering the fetched weather data as JSX elements within the WeatherApp component. The data is fetched from the OpenWeatherMap API as a JSON object, which is then unpacked and used to update the component's state
.
When the component's state is updated with the fetched weather data, the render method of the WeatherApp component is called. This method returns JSX elements that display the weather information, such as the city name, temperature, and weather description. The JSX elements are created using the data from the JSON object stored in the component's state
.
The networking with the OpenWeatherMap API server is done using the fetch function, which is a built-in JavaScript function for making HTTP requests. In the WeatherApp component, the fetch function is called with the API URL, which includes the city name and the API key. The response from the API server is then converted to a JSON object using the response.json() method. Once the JSON object is obtained, it is used to update the component's state, triggering a re-render and displaying the fetched weather data on the screen
.

## Conclusion
Congratulations! You have just built a simple weather application using React.js and the OpenWeatherMap API. This lab session has demonstrated the power of React.js for building interactive web applications, and the convenience of using a cloud-based IDE for development. Happy coding!




Citations: [1] https://www.amazon.com/React-Quickly-Painless-Redux-GraphQL/dp/1617293342 [2] https://codepen.io/tutsplus/pen/gObLaEP [3] https://thenewstack.io/are-cloud-based-ides-the-future-of-software-engineering/ [4] https://legacy.reactjs.org/docs/hello-world.html [5] https://github.com/async-labs/builderbook [6] https://codepen.io/thisoldbear/pen/YXoVgQ [7] https://dev.to/faisal00121/benefits-of-react-js-in-cloud-based-software-development-3gck [8] https://betterprogramming.pub/creating-a-simple-app-with-react-js-f6aa88998952 [9] https://www.coursehero.com/file/152196954/Lab13docx/ [10] https://youtube.com/watch?v=UjeXpct3p7M [11] https://www.ringcentral.com/gb/en/blog/definitions/cloud-ide/ [12] https://www.freecodecamp.org/news/how-to-build-a-react-app-different-ways/ [13] https://legacy.reactjs.org/docs/getting-started.html [14] https://javascript.plainenglish.io/build-a-real-time-weather-app-with-javascript-and-openweathermap-api-bcf8111df1fe [15] https://www.gmihub.com/blog/cloud-based-development/ [16] https://www.pluralsight.com/paths/building-web-applications-with-react [17] https://www.reddit.com/r/learnjavascript/comments/d5bz1h/javascript_weather_app_tutorial_using/ [18] https://www.reddit.com/r/webdev/comments/8y9z4e/looking_for_a_good_cloud_based_ide_for_react/ [19] https://www.pearson.com/store/p/learning-react-a-hands-on-guide-to-building-web-applications-using-react-and-redux/P200000000179/9780134843575 [20] https://youtube.com/watch?v=w0VEOghdMpQ [21] https://www.orientsoftware.com/blog/react-ide/ [22] https://www.oreilly.com/library/view/react-building-modern/9781786462268/ [23] https://youtube.com/watch?v=Reny0cTTv24 [24] https://che-kulhan.medium.com/cloud-based-ides-c545137c3536 [25] https://www.freecodecamp.org/news/react-beginner-handbook/
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.