Last active
May 10, 2016 17:40
-
-
Save sarkistlt/d202eae03edd85c1241f77f1525c5ab5 to your computer and use it in GitHub Desktop.
React component with weather-widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Import variables ***************************************************************************************************/ | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
/* React components ***************************************************************************************************/ | |
export default class Weather extends React.Component{ | |
constructor(props) { | |
super(props); | |
this.state = { | |
city: ``, | |
temp: ``, | |
icon: ``, | |
description: `` | |
}; | |
} | |
componentWillMount() { | |
let XHR = (`onload` in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest; //to support IE8 | |
let ipXhr = new XHR(), | |
weatherXhr = new XHR(), | |
THIS = this; | |
ipXhr.open(`GET`, `https://weathersync.herokuapp.com/ip`, true); | |
ipXhr.send(); | |
ipXhr.onreadystatechange = function () { | |
let lat = ``, | |
lng = ``; | |
if (ipXhr.readyState != 4) return; | |
if (ipXhr.status != 200) { | |
console.log(`error ${ipXhr.status}: ${ipXhr.statusText}`); | |
} else { | |
let ip = JSON.parse(ipXhr.responseText); | |
lat = ip.location.latitude; | |
lng = ip.location.longitude; | |
weatherXhr.open(`GET`, `https://weathersync.herokuapp.com/weather/${lat},${lng}`, true); | |
weatherXhr.send(); | |
weatherXhr.onreadystatechange = function () { | |
if (weatherXhr.readyState != 4) return; | |
if (weatherXhr.status != 200) { | |
console.log(`error ${weatherXhr.status}: ${weatherXhr.statusText}`); | |
} else { | |
let obj = JSON.parse(weatherXhr.responseText), | |
city = obj.name, | |
temp = Math.floor(1.8 * (obj.main.temp - 273) + 32), //Convert Kelvin to Fahrenheit | |
icon = `http://openweathermap.org/img/w/${obj.weather[0].icon}.png`, | |
description = obj.weather[0].description; | |
THIS.setState({city: city}); | |
THIS.setState({temp: `${temp} ºF`}); | |
THIS.setState({icon: icon}); | |
THIS.setState({description: description}); | |
} | |
} | |
} | |
}; | |
} | |
render() { | |
return ( | |
<div> | |
<h1>{this.state.city}</h1> | |
<p>{this.state.temp}</p> | |
<img src={this.state.icon}/> | |
<h2>{this.state.description}</h2> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment