Skip to content

Exercise 05 : Weather Forecast

Introduction

This exercise teaches how to load JSON data and show loaded data in a React application. Weather Forecast will be loaded with Axios from the OpenWeather. Application UI will be created with Material-UI components.

Image 01

Weather Forecast data

Find a free weather forecast provider, which offers XML or JSON data. You can use for example https://openweathermap.org/. Get your own API key, you will need it later in this exercise.

Note

Open Weather will/may ask you to give credit card information now. You can use any other weather API if you want. For example following Weather by API-Ninjas.

Material-UI

Material-UI offers React components for faster and easier web development. It is a design language that Google developed in 2014. It uses grid based layouts, responsive animations, transitions, padding, and depth effects such as lighting and shadow. It also offers commonly used Components to use in React Application. You should read Getting Started documentation first and play a little bit with different components and layouts.

React project

Create a new React project and name it to weather-app.

1
npx create-react-app weather-app

Install and use Axios

Install Axios and use it to load JSON data in your application.

1
npm install axios

Install Material-UI

Follow instructions found from the Material-UI site and install it to your project: Installation.

Start your app

Run your project and check that it works now correctly, before you start coding.

Modify app to use Material-UI

Modify your application to show just one default button.

1
2
3
4
5
6
7
function App() {
  return (
    <div>
      <button>Hit Me!</button>
    </div>
  );
}

Now you shold see just one button in browser.

Image 02

Import Material-UI to your project and use Button component.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import React from 'react';
import Button from '@mui/material/Button';

function App() {
  return (
    <div className="App">
      <Button variant="contained" color="primary">
        Hit Me!
      </Button>
    </div>
  );
}

export default App;

Now you shold see a button from Material-UI.

Image 03

Create application UI

Create UI where user can give a city name and remember user Material-UI components too. Remember that you need to import used Material-UI components.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<h1>React Weather Application</h1>
<p>
  This application will fetch a weather forecast from the OpenWeather.
  Just type city name and click Get Forecast button!
</p>
<form>
  <TextField label="Cityname" 
             defaultValue="Jyväskylä" 
             id="outlined-basic" 
             />
  <Button variant="contained" 
          color="primary" 
          size="small" 
          >
    Get Forecast
  </Button>
</form>

Image 04

Get cityname

You can use React Hooks to get cityname. Now Jyväskylä used by default.

1
const [cityname, setCityname] = useState("Jyväskylä")

And use onChange event in your TextField component to call above setCityName hook.

1
onChange={ (e) => setCityname(e.target.value)}

Call own made getWeather function, when a Button component is clicked.

1
onClick={() => getWeather()}
1
2
3
const getWeather = () => {
  console.log(cityname)
}

Test your app

Save and test your application. Type some cityname to TextField component and click Button. Open Browser's console to see cityname.

Image 05

Get Weather Forecast

Use Axios to load Weather Forecast from OpenWeather, when a Button component is clicked.

You can access current weather data for any location on Earth including over 200,000 cities with current weather data @ OpenWeather. Check and learn the API calls to get weather forecast by city name.

And a new weather hook to store weather forecast.

1
const [weather, setWeather] = useState(null);

Define some variables needed for OpenWeather API.

1
2
3
const API_KEY = 'your_api_key_here';
const URL = 'https://api.openweathermap.org/data/2.5/weather?q=';
const ICON_URL = 'http://openweathermap.org/img/wn/';

Modify getWeather function to use Axios.

1
2
3
4
5
6
7
8
const getWeather = () => {
  axios
    .get(URL+cityname+'&appid='+API_KEY+'&units=metric')
    .then(response => {
      // console.log(response.data) to see data in console
      setWeather(response.data)
    })
}

And finally show loaded weather forecast inside your app with conditional rendering.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<h2>Loaded weather forecast</h2>
{ weather !== null &&          
  <div>
    City: {weather.name}<br/>
    Main: {weather.weather[0].main}<br/>
    Temp: {weather.main.temp} °C<br/>
    Feels: {weather.main.feels_like} °C<br/>
    Min-Max: {weather.main.temp_min} - {weather.main.temp_max} °C<br/>
    <img
      alt={cityname} 
      style={{height: 100, width: 100}}
      src={ICON_URL+weather.weather[0].icon+'.png'}/>
</div>
}

{ weather === null &&
  <p>-</p>
}

Test

Save and test your app. It should work now.

Image 01

Use Environment variables

Now your Weather API key is included in your source codes and if you push your code to GitLab, it is visible to everyone.

Steps

  • Create .env file to your project folder
  • Add your key to .env file REACT_APP_WEATHER_APIKEY = YOUR_API_KEY_HERE
  • Use it in your code const API_KEY = process.env.REACT_APP_WEATHER_APIKEY;

Now your API key isn't visible to everyone.

Push exercise 05 / Weather to GitLab

Test your application in web browser, take screenshots and commit/push your project and screenshots back to JAMKIT/GitLab. Remember move your exercise/issue ticket from Doing to In Review in Issues Board and write your learning comments to issue comments.

Save screenshots to weather-app folder.