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

Lab Checklist:

Signup for
___ OpenWeather API key
Start by setting up a Node Project on
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

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
1. Navigate to 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:
- -

### 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('') .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 {}</h1> <h2>{Math.round(weatherData.main.temp - 273.15)}°C</h2> <p>{[0].description}</p> </div> ); } }
ReactDOM.render(<WeatherApp />, document.getElementById('app')); ```
Remember to replace `YOUR_API_KEY` with your actual API key from OpenWeatherMap[14].

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={} onChange={this.handleInputChange} /> <input type="submit" value="Get Weather" /> </form> <h1>Weather in {}</h1> <h2>{Math.round(weatherData.main.temp - 273.15)}°C</h2> <p>{[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: }); }
handleSubmit(event) { event.preventDefault(); this.fetchWeatherData(; } ```
Finally, we need to modify the `componentDidMount` method to `fetchWeatherData` method and call this method in `handleSubmit`:
```javascript fetchWeatherData(city) { fetch(`${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] [2] [3] [4] [5] [6]

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] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.