Skip to content

Instantly share code, notes, and snippets.

@bartimaeus
Created August 16, 2018 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bartimaeus/45021a3afd9fccc14f0b75cf5a1e89e2 to your computer and use it in GitHub Desktop.
Save bartimaeus/45021a3afd9fccc14f0b75cf5a1e89e2 to your computer and use it in GitHub Desktop.
Lesson 05
////////////////////////////////////////////////////////////////////////////////
// Exercise:
//
// - Refactor App by creating a new component named `<GeoPosition>`
// - <GeoPosition> should use a render prop callback that passes
// the coords and error
// - When you're done, <App> should no longer have anything but
// a render method
// - Now create a <GeoAddress> component that also uses a render
// prop callback with the current address. You will use
// `getAddressFromCoords(latitude, longitude)` to get the
// address. It returns a promise.
// - You should be able to compose <GeoPosition> and <GeoAddress>
// beneath it to naturally compose both the UI and the state
// needed to render
// - Make sure <GeoAddress> supports the user moving positions
import "./index.css";
import React from "react";
import LoadingDots from "./LoadingDots";
import Map from "./Map";
import getAddressFromCoords from "./getAddressFromCoords";
class GeoLocation extends React.Component {
state = {
coords: null,
error: null
};
componentDidMount() {
this.geoId = navigator.geolocation.watchPosition(
position => {
this.setState({
coords: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
});
},
error => {
this.setState({ error });
}
);
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.geoId);
}
render() {
return this.props.children(this.state);
}
}
class Address extends React.Component {
state = {
coords: this.props.coords,
address: null
};
async componentDidMount() {
const { coords: { lat, lng } } = this.props;
const address = await this.getAddress(lat, lng);
// console.log("address", address);
this.setState({ address });
}
getAddress = async (lat, lng) => {
const response = await getAddressFromCoords(lat, lng);
return response;
};
render() {
return this.props.children(this.state);
}
}
class App extends React.Component {
render() {
return (
<GeoLocation>
{state => (
<div className="app">
{state.error ? (
<div>Error: {state.error.message}</div>
) : state.coords ? (
<Address coords={state.coords}>
{({ address }) => (
<Map
lat={state.coords.lat}
lng={state.coords.lng}
info={address || "You are here"}
/>
)}
</Address>
) : (
<LoadingDots />
)}
</div>
)}
</GeoLocation>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment