Ad

What Is The Right Way To Use Ionic Native / Cordova Plugins With Ionic (React) & Capacitor?

- 1 answer

How can I use Ionic Native / Cordova Plugins with Ionic React (not Angular) using Capacitor instead of Cordova?

I want to make use of Screen Orientation Plugin with Capacitor and Ionic React. This is because Cordova is not officially supported for Ionic React projects. Know More.

This is what I have tried.

import { ScreenOrientation } from '@ionic-native/screen-orientation'
.
.
.
.
useEffect(() => {
    ScreenOrientation.lock(ScreenOrientation.ORIENTATIONS.LANDSCAPE)
}, [])

My package.json has the following relevant dependencies installed.

"@ionic-native/core": "^5.13.0",
"@ionic-native/screen-orientation": "^5.13.0",
"cordova-plugin-screen-orientation": "^3.0.2"

The application builds successfully, but still opens in Portrait mode on my Android device. If I try to display the following,

console.log(ScreenOrientation.type)

The app builds successfully, but the screen goes blank.

Capacitor's Native APIs work flawlessly with Ionic React. For example,

import { Plugins } from '@capacitor/core'
const { StatusBar } = Plugins
.
.
useEffect(() => {
    StatusBar.hide()
}, [])

Will hide the status bar on my Android device.

Is this the right approach for using Cordova Plugins with Capacitor in Ionic React? Reference

If yes, what am I doing wrong here? And if no, how can I achieve the same?

Ad

Answer

Problem solved! I was doing everything right, I had just forgotten to run npx cap sync after installing my Ionic Native Plugin.

So, the right way to use Cordova Plugins with Capacitor & Ionic (React) is

npm install @ionic-native/javascript-package-name
npm install cordova-plugin-name
npx cap sync
Ad
source: stackoverflow.com
Ad