Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onDeviceReady event listener in react component

In my react app, I am trying to use a Cordova plugin (cordovo-plugin-device) to get user's device version as follows

class LogoHeader extends React.Component {
  componentDidMount () {
    window.addEventListener('deviceready', this.onDeviceReady)
  }
  onDeviceReady () {
    console.log(device.cordova)
  }
  render () {
    ...
  }
}

But for some reason, the deviceready event never gets fired. Am I missing something? Is there a better way to listen to DOM events in react ?

like image 975
MetaTom Avatar asked Aug 08 '18 05:08

MetaTom


1 Answers

According to Cordova docs and this SO answer you should add the listener in your entry file (probably index.js)

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

const startApp = () => {
    console.log(device.cordova)
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    );
}

if(!window.cordova) {
  startApp()
} else {
  document.addEventListener('deviceready', startApp, false)
}

You could also pass down device.cordova as props to App so you could access it in other components.

...
ReactDOM.render(
      <App device={device
         ? device.cordova
         : null}/>,
      document.getElementById('root')
    );
...
like image 156
StackedQ Avatar answered Nov 10 '22 08:11

StackedQ