Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to use Ionic Native / Cordova Plugins with Ionic (React) & Capacitor?

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?

like image 948
Indrajeet Patil Avatar asked Sep 04 '19 11:09

Indrajeet Patil


People also ask

Does Ionic still support Cordova?

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.

Can I use Cordova plugin in React Native?

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.

Can we use React Native with Ionic?

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.


1 Answers

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
like image 177
Indrajeet Patil Avatar answered Oct 28 '22 20:10

Indrajeet Patil