Best practice for importing mobile-only capacitor plugins?

I have an Ionic React app and I want to use the Capacitor Keyboard plugin on my login screen.

My code looks something like this:

import { Keyboard } from '@capacitor/keyboard';

...MyComponent
  const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);

  Keyboard.addListener('keyboardWillShow', (info) => {
    console.log('keyboard will show with height:', info.keyboardHeight);
    setIsKeyboardVisible(true);
  });
  Keyboard.addListener('keyboardDidHide', () => {
    console.log('keyboard will hide');
    setIsKeyboardVisible(false);
  });

          {!isKeyboardVisible && (
            <ButtonLanguageChanger />
          )}

This crashes my app on the web:

util.js:21 Uncaught (in promise) Error: "Keyboard" plugin is not implemented on web
    at createPluginMethod (runtime.js:70)
    at runtime.js:77

I understand that the Keyboard plugin doesn’t work on the web, but what’s the best practice for importing such plugins in React? (I want to use it on mobile, and just ignore it on the web.)

This is the solution I came up with:

  if (isPlatformMobile()) {
    Keyboard.addListener('keyboardWillShow', (info) => {
      console.log('keyboard will show with height:', info.keyboardHeight);
      setIsKeyboardVisible(true);
    });
    Keyboard.addListener('keyboardDidHide', () => {
      console.log('keyboard will hide');
      setIsKeyboardVisible(false);
    });
  

export const isPlatformMobile = (): boolean => (isPlatform('capacitor'));

But I’d like to hear if there is a better way.

@ptmkenny But this is not working on mobileweb browser. It still shows the error on mobilebrowsers

I personally check if capacitor run on native platform.

import {Capacitor} from "@capacitor/core";
....


if (Capacitor.isNativePlatform()) {
    Keyboard.addListener(...
}

This will be more apt, this checks for the presence of Plugin before calling to avoid the errors like: Non-Error promise rejection captured with value: Keyboard does not have web implementation.

import {Capacitor} from "@capacitor/core";
....


if (Capacitor. isPluginAvailable('Keyboard')) {
    Keyboard.addListener(...
}