A simple weather app is something everyone should try making as it make us familiar with basics of API handling.
The Layout
So first what we have to create is a layout in which there will be a search box where city name can be entered and a card kind of thing where output can be shown.
The Card can contain City name, temperature, etc.. Will talk it about in API Section
Design the cards and input as per your creativity.
The API we are using
For this weather app we will be using OpenWeatherMap/API as it's free and easy to use.
To Start using it you should have an API key so first register yourself on this website and get the keys.
Click Here to get The API Key after signing up
Now Come to the JavaScript Part
First, bring all the DOM elements to JavaScript and add
.onsubmit
eventlistner to Form and get the text input valueNow we will create a function through which we will pass this city name and it will get the data from API and update the DOM
There are various methods to use API in JavaScript but we will be using the basic one the
XMLHttpRequest();
using XHR in JS is simple just add
const xhr = new XMLHttpRequest(); xhr.open('GET',url); xhr.send(); xhr.onload = () =>{ // we can change the data type to json also by const data = JSON.prase(xhr.response); console.log(data); };
this Handles API
in the place of url use https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR-TOKEN-GOES-HERE
this will return a object containing info of particular city.
First
console.log(data);
pressShift+Ctrl+J
to check the console and observe the object
it give a lot of data, Now what we have to do is change DOM accordingly.Use
ELEMENT-SELETOR.innerHTML='THE-DATA'
to Change the value in DOMThis API also returns a image for the weather and can be accessed from
data.weather[0].icon
it will give the icon name change the src of image tohttp://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png
To know more see the weather-icon docs
Check the pen to get more idea.
In this I have used OpenWeatherMap/Current API to get current data you can also explore other on OpenWeatherMap/API
Please use you API KEY don't burden my one too much as it's free to create one but have daily limits.
Read Also:
Why to use React if HTML/CSS/JS works fine?
Areeb ur Rub ・ May 29 '21
#discuss #webdev #react #javascript
Follow me for more:
Top comments (2)
Have you thought about using fetch instead of XMLHttpRequest? It is much more modern, but anyway, good work!
Yeah, I know about
fetch( )
and Axios as well but I wanted to use XHR here.