Nuxtstop

For all things nuxt.js

Access to Location, Network Status and other Browser Provided Properties in React

7 0

Browsers are becoming more and more powerful. Nowadays, browser can provide information about your network status (either you are online or offline), your location (geographic coordinates) among a million other things. Perhaps, the most intriguing thing is that you can even access the haptic engine in your device through your browser.

But how do we leverage this power?

Well, Navigator interface (windows.navigator) provides an API to do so!

However, it is good to take advantage what React has to offer, namely hooks!

Here is an example how you would access the location with the react-browser-navigator NPM package after installing the the package with npm install react-browser-navigator:

// import the module
import useNavigator from "react-browser-navigator";

function App() {
  // accessible properties
  let { getCurrentPosition } = useNavigator();

  // getCurrentPosition
  useEffect(() => {
    if (!isNull(getCurrentPosition)) {
      // printing out the entire object
      console.log("getCurrentPosition", getCurrentPosition);
    }
  }, [getCurrentPosition]);

  return (
    <div>
      <span>Latidude:</span> {getCurrentPosition?.coords.latitude}
      <br />
      <br />
      <span>Longitude:</span> {getCurrentPosition?.coords.longitude}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

There are lots of other properties that you can access. For instance, are you onLine or not?!

// import the module
import useNavigator from "react-browser-navigator";

function App() {
  // list accessible navigator properties (find them all below in a table)
  let { networkStatus } = useNavigator();

  return (
    <div>
      {networkStatus === true ? (
        <span>We are online!</span>
      ) : (
        <span>We are offline!</span>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Head over to the package's page to see more.

There is also an extended roadmap to add more properties.