forked from ericvicenti/intro-to-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-Lifecycle-and-Data-App.js
74 lines (70 loc) · 1.85 KB
/
3-Lifecycle-and-Data-App.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import React, { Component } from "react";
import "./App.css";
const PLACES = [
{ name: "Palo Alto", zip: "94303" },
{ name: "San Jose", zip: "94088" },
{ name: "Santa Cruz", zip: "95062" },
{ name: "Honolulu", zip: "96803" }
];
class WeatherDisplay extends Component {
constructor() {
super();
this.state = {
weatherData: null
};
}
componentDidMount() {
const zip = this.props.zip;
const URL = "http://api.openweathermap.org/data/2.5/weather?q=" +
zip +
"&appid=b1b35bba8b434a28a0be2a3e1071ae5b&units=imperial";
fetch(URL).then(res => res.json()).then(json => {
this.setState({ weatherData: json });
});
}
render() {
const weatherData = this.state.weatherData;
if (!weatherData) return <div>Loading</div>;
const weather = weatherData.weather[0];
const iconUrl = "http://openweathermap.org/img/w/" + weather.icon + ".png";
return (
<div>
<h1>
{weather.main} in {weatherData.name}
<img src={iconUrl} alt={weatherData.description} />
</h1>
<p>Current: {weatherData.main.temp}°</p>
<p>High: {weatherData.main.temp_max}°</p>
<p>Low: {weatherData.main.temp_min}°</p>
<p>Wind Speed: {weatherData.wind.speed} mi/hr</p>
</div>
);
}
}
class App extends Component {
constructor() {
super();
this.state = {
activePlace: 0
};
}
render() {
const activePlace = this.state.activePlace;
return (
<div className="App">
{PLACES.map((place, index) => (
<button
key={index}
onClick={() => {
this.setState({ activePlace: index });
}}
>
{place.name}
</button>
))}
<WeatherDisplay key={activePlace} zip={PLACES[activePlace].zip} />
</div>
);
}
}
export default App;