useGeolocation
Aboutβ
A hook to provide the geolocation info on client side.
Installationβ
npm install --save rooks
Importing the hookβ
import { useGeolocation } from "rooks";
Usageβ
1. Getting geolocation in a componentβ
function App() {
const geoObj = useGeolocation();
return (
<div
style={{
display: "flex",
alignItems: "center",
flexDirection: "column",
}}
>
<p>{geoObj && JSON.stringify(geoObj)}</p>
</div>
);
}
render(<App />);
2. Getting geolocation in a component on some conditionβ
function App() {
const [when, setWhen] = React.useState(false);
const geoObj = useGeolocation({
when,
});
return (
<div
style={{
display: "flex",
alignItems: "center",
flexDirection: "column",
}}
>
<button
onClick={() => {
setWhen(true);
}}
>
Get Geolocation
</button>
<p>{geoObj && JSON.stringify(geoObj)}</p>
</div>
);
}
render(<App />);
Argumentsβ
The argument is an object with the following optional items:
Argument value | Type | Description |
---|---|---|
options.enableHighAccuracy | boolean | enable high accuracy if true |
options.timeout | number | timeout in milliseconds |
options.maximumAge | number | maximumAge in milliseconds |
options.when | boolean | this hook will run when when is true |
Returnsβ
Returns an object with following items:
{
lat?: number;
lng?: number;
isError: boolean;
message: string;
}
Codesandbox Exampleβ
Basic Usageβ
Join Bhargav's discord serverβ
You can click on the floating discord icon at the bottom right of the screen and talk to us in our server.