Sergio Xalambrí

React Hook: usePermissions

React Hook for the Permissions API.

Installation

Install it using yarn with the command.

yarn add react-use-permissions

Or using npm with the command.

npm install react-use-permissions

Usage

Import it inside the application.

import usePermissions from "react-use-permissions";

Then use it inside any functional React component passing any valid name.

Valid names are accelerometer, accessibility-events, ambient-light-sensor, background-sync, camera​, clipboard-read, clipboard-write, geolocation, gyroscope, magnetometer, microphone, midi, notifications, payment-handler, persistent-storage, and push

const format = function Component() {
  const hasPermissions = usePermissions("geolocation");
  const content = (() => {
    switch (hasPermissions) {
      // User has granted permissions
      case true: {
        return "Permissions granted";
      }
      // User has denied permissions
      case false: {
        return "Permissions denied";
      }
      // User will be prompted for permissions
      case null: {
        return "Asking for permissions";
      }
    }
  })();
  return <h1>{content}</h1>;
};

When the component is rendered the hook will return null initially and then check if the user has already granted or denied the permissions returning a boolean. In case the user hasn't already it will be prompted and then the hook will return the new state.