Created
June 23, 2019 06:28
-
-
Save cdsandoval/be19bd043ed5651bdaa09cb3098f4116 to your computer and use it in GitHub Desktop.
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
HOC is a function with a component that return a new component. | |
//geolocation.js | |
function withGeolocation(Component) { | |
function Geolocation() { | |
const [latitude, setLatitude] = React.useState(0); | |
const [longitude, setLongitude] = React.useState(0); | |
React.useEffect(() => { | |
const watchId = navigator.geolocation.watchPosition(({ coords }) => { | |
setLatitude(coords.latitude); | |
setLongitude(coords.longitude); | |
}); | |
return () => navigator.geolocation.clearWatch(watchId); | |
}, [setLatitude, setLongitude]); | |
return <Component latitude={latitude} longitude={longitude} />; | |
} | |
return Geolocation; | |
} | |
export default withGeolocation; | |
// index.js | |
import React from "react"; | |
import { Map, TileLayer, Marker } from "react-leaflet"; | |
import { render } from "react-dom"; | |
import withGeolocation from "./geolocation"; | |
function App({ latitude, longitude }) { | |
return ( | |
<Map center={[latitude, longitude]} zoom={15}> | |
<TileLayer | |
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" | |
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors | Made for Codeable' | |
/> | |
<Marker position={[latitude, longitude]} /> | |
</Map> | |
); | |
} | |
const GeoApp = withGeolocation(App); | |
const $root = document.getElementById("root"); | |
render(<GeoApp />, $root); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment