Originally published at https://sdx.im/articles/libs/react-use-permissions
React hook for Permissions API.
Note: This is using the new React Hooks API Proposal which is subject to change until React its final release.
You'll need to installreact
,react-dom
, etc at^16.7.0-alpha.0
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
, andpush
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.
sergiodxa / react-use-permissions
React hook for Permissions API
react-use-permsissions
React Hook for the Permissions API
Install
yarn add react-use-permissions
Usage
import usePermissions from '../src';
const format = hasPermissions => {
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";
}
}
}
function App() {
const hasPermissions = usePermissions("geolocation");
const content = format(hasPermissions);
return <h1>{content}</h1>;
}
Top comments (1)
This looks helpful as React is now in Preview.
And would you add the link to the repo by chance?
You can show the repo using following 👇 syntax
, which will display the repo like this.
sergiodxa / react-use-permissions
React hook for Permissions API
react-use-permsissions
Install
Usage