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?
While developers can still use Cordova in the Ionic stack, the future is Ionic with Capacitor (or Capacitor on its own with any popular web stack!). These apps are known as Web Native apps, in contrast to the older hybrid approach.
The Cordova plugin ecosystem is diverse and rich. Many native device capabilities are already available as a plugin with a W3C like Javascript API in most cases. Using them to access native capabilities from React Native can be done using Cordova plugins without having to rewrite all those plugins.
Build awesome apps across mobile, desktop, and web, with the React you know and love. Ionic React is native React version of Ionic Framework, the free, open source SDK powering millions of mission-critical apps all over the world. It's everything you need to ship award-winning apps for any platform, with React.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With