• Stars
    star
    244
  • Rank 165,885 (Top 4 %)
  • Language
    TypeScript
  • License
    Other
  • Created almost 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚡️ React hooks for Capacitor ⚡️


Capacitor React Hooks

A set of hooks to help Capacitor developers use native Capacitor APIs.


Maintainers

Maintainer GitHub Social
Ely Lucas elylucas @elylucas

These docs are for Capacitor 3 plugins. For docs that target v2 plugins, see the capv2 branch.

Getting Started

To start using Capacitor Hooks in your app, you install the React Hook package along with the Capacitor plugin you want to use. Here is an example of using the Storage plugin along with it's React hook:

# Install the Capacitor Plugin
npm install @capacitor/storage 
# And then the React hook package:
npm install @capacitor-community/storage-react

Import the hooks:

import { useStorage } from '@capacitor-community/storage-react'

Then use the hooks in your app:

const [value, setValue] = useStorage('mykey');

Feature Detection

While Capacitor allows you to write to one API across several platforms, not all features are supported on all platforms. It is encouraged to check if the feature you intend to use is available before using it to avoid any runtime errors.

Each of the hook plugin paths exports an availableFeatures object, which contains a list features for that plugin. If the feature is supported for the current platform the app is running on, that feature will be true:

const { useStorageItem, availableFeatures } = `@capacitor-community/storage-react`;
const [value, setValue] = useStorage('mykey');
...
if(availableFeatures.useStorage) {
  // Storage is available, feel free to use it!
  setValue('cake');
}

Upgrading from Capacitor 2 React Hooks

In Capacitor 3, all the plugins were separated into their own packages. Likewise, the new React hooks plugins were also put into their own package, so you will need to install the hook for each plugin you use.

Any deprecated API'S from Capacitor 2 to 3 were also removed and updated, so you might need to make some modifications to account for API changes. See the Capacitor Plugin API for to learn more.

Hook Usage

@capacitor/app Hooks

Installation:

npm install @capacitor-community/app-react

Usage:

import { useAppState, useAppUrlOpen, useLaunchUrl, availableFeatures } from '@capacitor-community/app-react';

useAppState provides access to App status information, such as whether the app is active or inactive. This value will update dynamically.

const {state} = useAppState();

useLaunchUrl

useLaunchUrl provides the URL the app was initially launched with. If you'd like to track future inbound URL events, use useAppUrlOpen below instead.

const { launchUrl } = useLaunchUrl();

useAppUrlOpen

useAppUrlOpen provides the most recent URL used to activate the app. For example, if the user followed a link in another app that opened your app.

const { appUrlOpen } = useAppUrlOpen();

See the App Capacitor Plugin docs for more info on the plugin API.

@capcitor/browser Hooks

Installation:

npm install @capacitor-community/browser-react

Usage:

import { useClose, useOpen, availableFeatures } from '@capacitor-community/browser-react';

useOpen, useClose provides a way to launch, and close an in-app browser for external content:

// Open url in browser
const { open } = useOpen();

open({ url: 'http://ionicframework.com' });

// Close url in browser
const { close } = useClose();
useClose();

See the Browser Capacitor Plugin docs for more info on the plugin API.

@capacitor/camera Hooks

Installation:

npm install @capacitor-community/camera-react

Usage:

import { useCamera, availableFeatures } from '@capacitor-community/camera-react';

useCamera provides a way to take a photo:

const { photo, getPhoto } = useCamera();
const triggerCamera = useCallback(async () => {
  getPhoto({
      quality: 100,
      allowEditing: false,
      resultType: CameraResultType.DataUrl
    })
}, [getPhoto]);

<div>{photo && <img alt="" src={photo.dataUrl} />}</div>

See the Camera Capacitor Plugin docs for more info on the plugin API.

Clipboard Hooks

Installation:

npm install @capacitor-community/clipboard-react

Usage:

import { useClipboard, availableFeatures } from '@capacitor-community/clipboard-react';

useClipboard reads and writes clipboard data:

const { value, getValue, setValue } = useClipboard();

const paste = useCallback(async () => {
  await setValue('http://ionicframework.com/);
}, [setValue]);

const copy = useCallback(async () => {
  getValue(); 
}, [getValue])

See the Clipboard Capacitor Plugin docs for more info on the plugin API.

Device Hooks

Installation:

npm install @capacitor-community/device-react

Usage:

import { useGetInfo, useGetLanguageCode, availableFeatures } from '@capacitor-community/device-react';

useGetInfo, useGetLanguageCode gives access to device information and device language settings:

const { info } = useGetInfo();
const { languageCode } = useGetLanguageCode();

See the Device Capacitor Plugin docs for more info on the plugin API.

Filesystem Hooks

Installation:

npm install @capacitor-community/filesystem-react

Usage:

import { useFilesystem, base64FromPath, availableFeatures } from '@capacitor-community/filesystem-react';

useFilesystem returns back common methods to gain access to file system apis.

const { readFile } = useFilesystem();

const file = await readFile({
  path: filepath,
  directory: FilesystemDirectory.Data
});

base64FromPath is a helper method that will take in a path to a file and return back the base64 encoded representation of that file.

See the Filesystem Capacitor Plugin docs for more info on the plugin API.

const base64String = await base64FromPath(path);

Geolocation Hooks

Installation:

npm install @capacitor-community/geolocation-react

Usage:

import { useCurrentPosition, useWatchPosition, availableFeatures } from '@capacitor-community/geolocation-react';

useCurrentPosition returns a single geolocation position using the Geolocation API in Capacitor. The position can be manually updated by calling getPosition:

const { currentPosition, getPosition } = useCurrentPosition();

const handleRefreshPosition = () => {
  getPosition();
}

useWatchPosition tracks a geolocation position using the watchPosition in the Geolocation API in Capacitor. The location will automatically begin updating, and you can use the clearWatch and startWatch methods to manually stop and restart the watch.

const { currentPosition, startWatch, clearWatch } = useWatchPosition();

See the Geolocation Capacitor Plugin docs for more info on the plugin API.

Keyboard Hooks

Installation:

npm install @capacitor-community/keyboard-react

Usage:

import { useKeyboardState } from '@capacitor-community/keyboard';

useKeyboard returns whether or not the on-screen keyboard is shown as well as an approximation of the keyboard height in pixels.

const { isOpen, keyboardHeight } = useKeyboard();
// Use keyboardHeight to translate an input that would otherwise be hidden by the keyboard

See the Keyboard Capacitor Plugin docs for more info on the plugin API.

Network Hooks

Installation:

npm install @capacitor-community/network-react

Usage:

import { useStatus, availableFeatures } from '@capacitor-community/network-react';

useStatus monitors network status and information:

 const { networkStatus } = useStatus();

See the Network Capacitor Plugin docs for more info on the plugin API.

ScreenReader Hooks

Installation:

npm install @capacitor-community/screen-reader-react

Usage:

import { useIsScreenReaderEnabled, useSpeak, availableFeatures } from '@capacitor-community/screen-reader-react';

useIsScreenReaderEnabled provides access to detecting and responding to a screen reading device or OS setting being enabled:

const {isScreenReaderEnabled} = useIsScreenReaderEnabled();

useSpeak activates a text-to-speech engine (if available) to read spoken text.

const { speak } = useSpeak();
speak({value: textToSpeak})

See the ScreenReader Capacitor Plugin docs for more info on the plugin API.

Storage Hooks

Installation:

npm install @capacitor-community/storage-react

Usage:

import { useStorage, useStorageItem, availableFeatures } from '@capacitor-community/storage-react';

useStorage provides access to Capacitor's storage engine. There is also a helper called useStorageItem which makes managing a single item easy if you don't need to access the full Storage API (see below)

const { get, set, remove, getKeys, clear } = useStorage();
useEffect(() => {
  async function example() {
    const value = await get('name');
    await set('name', 'Max');
    await remove('name');
    const allKeys = await getKeys();
    await clear();
  }
}, [ get, set, remove, keys, clear ]);

useStorageItem

useStorageItem tracks a single item and provides a nice way to read and write that item:

const [ name , setName ] = useStorageItem('name', 'Max');

// Example:
const updateName = useCallback((n) => {
  setName(n);
}, [ setName ]);

useStorageItem will use the initial value already in storage, or the one provided if there is no existing value.

See the Storage Capacitor Plugin docs for more info on the plugin API.

Other Hooks

This is an evolving project and not all of the Capacitor Plugins are supported yet. If there is one you need, feel free top open an issue for it, or better yet, submit a PR!

More Repositories

1

sqlite

Community plugin for native & electron SQLite databases
Swift
463
star
2

barcode-scanner

A fast and efficient (QR) barcode scanner for Capacitor
Java
435
star
3

electron

Deploy your Capacitor apps to Linux, Mac, and Windows desktops, with the Electron platform! 🖥️
TypeScript
327
star
4

bluetooth-le

Capacitor plugin for Bluetooth Low Energy
TypeScript
277
star
5

fcm

Enable Firebase Cloud Messaging for Capacitor apps
TypeScript
240
star
6

generic-oauth2

Generic Capacitor OAuth 2 client plugin. Stop the war in Ukraine!
Java
232
star
7

admob

Community plugin for using Google AdMob
Java
209
star
8

http

Community plugin for native HTTP
Java
209
star
9

camera-preview

Capacitor plugin that allows camera interaction from HTML code
Java
188
star
10

stripe

Stripe Mobile SDK wrapper for Capacitor
Java
188
star
11

background-geolocation

A Capacitor plugin that sends you geolocation updates, even while the app is in the background.
Java
187
star
12

google-maps

Capacitor Plugin using native Google Maps SDK for Android and iOS.
Java
152
star
13

in-app-review

Let users rate your app using native review app dialog for both Android and iOS.
TypeScript
144
star
14

apple-sign-in

Sign in with Apple Support
Swift
137
star
15

vue-cli-plugin-capacitor

A Vue CLI 3/4 Plugin for Capacitor
JavaScript
131
star
16

keep-awake

⚡️ Capacitor plugin to prevent devices from dimming or locking the screen.
Java
125
star
17

firebase-analytics

Enable Firebase Analytics for Capacitor Apps
Java
122
star
18

contacts

Contacts Plugin for Capacitor
Java
114
star
19

tauri

Deploy your Capacitor apps to Linux, Mac, and Windows desktops, with the Tauri platform! 🖥️
TypeScript
108
star
20

native-audio

Java
104
star
21

facebook-login

Facebook Login support
Java
101
star
22

media

Capacitor plugin for saving and retrieving photos and videos, and managing photo albums.
TypeScript
100
star
23

text-to-speech

⚡️ Capacitor plugin for synthesizing speech from text.
Java
93
star
24

speech-recognition

Java
84
star
25

date-picker

Native DateTime Picker Plugin for Capacitor Apps
Swift
84
star
26

privacy-screen

⚡️ Capacitor plugin that protects your app from displaying a screenshot in Recents screen/App Switcher.
Swift
77
star
27

proposals

Plugin and platform requests ✋
74
star
28

app-icon

Capacitor plugin to programmatically change the app icon.
Java
74
star
29

firebase-crashlytics

⚡️ Capacitor plugin for Firebase Crashlytics.
Java
70
star
30

file-opener

Capacitor File Opener. The plugin is able to open a file given the mimeType and the file uri. This plugin is similar to cordova-plugin-file-opener2 without installation support.
Swift
64
star
31

intercom

Enable Intercom for Capacitor apps
TypeScript
57
star
32

photoviewer

PhotoViewer table images with fullscreen and sharing capabilities
Swift
49
star
33

examples

Examples of using Capacitor with popular web frameworks and libraries
JavaScript
46
star
34

safe-area

Capacitor Plugin that exposes the safe area insets from the native iOS/Android device to your web project.
Kotlin
46
star
35

welcome

Introduction to the Capacitor Community org 👋
37
star
36

appcenter-sdk-capacitor

Capacitor Plugin for Microsoft's Visual Studio App Center SDK.
TypeScript
35
star
37

in-app-purchases

WIP: In App Purchases plugin for Capacitor
Java
27
star
38

native-market

Java
26
star
39

realm

Java
25
star
40

firebase-remote-config

TypeScript
23
star
41

screen-brightness

Java
23
star
42

.github

Template repo for new community plugins
17
star
43

twitter

Capacitor plugin to enable TwitterKit
TypeScript
11
star
44

card-scanner

Simple card scanner for Capacitor Applications.
Swift
11
star
45

flipper

Java
10
star
46

auth0

TypeScript
9
star
47

volume-buttons

Capacitor Volume Buttons. The plugin enables to listen to hardware volume button presses. This plugin is based on https://github.com/thiagobrez/capacitor-volume-buttons
Swift
7
star
48

google-maps-examples

Vue
5
star
49

uxcam

UXCam and FullStory app analytics
Java
5
star
50

advertising-id

Allows access to the IDFA (iOS) and AAID (Android)
Swift
5
star
51

android-security-provider

Capacitor plugin with method to check and update the Android Security Provider.
Java
3
star
52

tap-jacking

Capacitor plugin to prevent tap jacking on Android devices
Java
2
star
53

mdm-appconfig

Capacitor community plugin for reading app configurations written by a MDM (see appconfig.org) such as VMWare Workspace One.
Java
2
star
54

exif

This plugin offers utility functions for interacting with image exif metadata
Swift
2
star
55

play-integrity

A Capacitor plugin to use the Play Integrity API
Java
1
star
56

device-check

A Capacitor plugin to use Apple's DeviceCheck API
Java
1
star