Skip to content

Instantly share code, notes, and snippets.

@cdsandoval
Created June 23, 2019 06:28
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 cdsandoval/be19bd043ed5651bdaa09cb3098f4116 to your computer and use it in GitHub Desktop.
Save cdsandoval/be19bd043ed5651bdaa09cb3098f4116 to your computer and use it in GitHub Desktop.
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='&copy; <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