Skip to content

Instantly share code, notes, and snippets.

@enesien
Last active October 25, 2023 15:43
Show Gist options
  • Save enesien/5e64d0f29235ece5ecefad025110caf7 to your computer and use it in GitHub Desktop.
Save enesien/5e64d0f29235ece5ecefad025110caf7 to your computer and use it in GitHub Desktop.
Capacitor initialization hook for React or Next.js apps
import { Capacitor } from "@capacitor/core";
import { Device } from "@capacitor/device";
import { SplashScreen } from "@capacitor/splash-screen";
import { StatusBar, Style } from "@capacitor/status-bar";
import { useState, useEffect } from "react";
interface CapacitorHookOptions {
color: string;
iosStyle: 'dark' | 'light';
androidStyle: 'dark' | 'light';
}
/**
* Hook that initializes Capacitor in your React/Next.js app that accounts for platform-specific
* bugs and caveats. Safe to use on web, Android and iOS.
*
* Place in your root component, for Next.js that's _app.ts
*
* @param options
*/
export const useCapacitor = (options: CapacitorHookOptions) => {
const [checked, setChecked] = useState(false);
useEffect(() => {
if (!checked) {
(async () => {
setChecked(true);
// native stuff
if (Capacitor.isNativePlatform()) {
// android-specific stuff
if (Capacitor.getPlatform() === "android") {
const info = await Device.getInfo();
const sdk = info.androidSDKVersion || 0;
// on android 13+, we need to hide splash first and wait 500ms before working with the status bar
if (sdk >= 33) {
await SplashScreen.hide({ fadeOutDuration: 500 });
await new Promise(resolve => setTimeout(resolve, 500))
await StatusBar.setStyle({ style: options.androidStyle === 'dark' ? Style.Dark : Style.Light });
await StatusBar.setBackgroundColor({ color: options.color });
}
// this is the normal, ideal flow for android 12 and below
else {
await StatusBar.setStyle({ style: options.androidStyle === 'dark' ? Style.Dark : Style.Light });
await StatusBar.setBackgroundColor({ color: options.color });
await SplashScreen.hide({ fadeOutDuration: 500 });
}
}
// ios-specific stuff
else {
await StatusBar.setStyle({ style: options.iosStyle === 'dark' ? Style.Dark : Style.Light });
await SplashScreen.hide({ fadeOutDuration: 500 });
}
}
})();
}
}, [checked]);
}
@enesien
Copy link
Author

enesien commented Oct 25, 2023

Hook that initializes Capacitor in your React/Next.js app that accounts for platform-specific bugs and caveats. Safe to use on web, Android and iOS.

Place in your root component, for Next.js that's _app.ts:

useCapacitor({
  color: "#4f46e5",
  androidStyle: "dark",
  iosStyle: "light",
});

From enesien

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment