I'm currently experimenting with React JS (v.0.14) and cordova. I want to read some files from the sdcard of an Android Emulator with the cordova file plugin.
When I try to start the app, I always got the error, that cordova.file.*
is undefined. This happens because, the React Components are rendered before the cordova onDeviceReady
is called. I added the ReactDOM.render
function inside of the onDeviceReady
function, but that don't work.
app.js
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
console.log('on ready'); // Update DOM on a Received Event
ReactDOM.render(
<App />,
document.getElementById('app')
);
}
};
app.initialize();
var App = React.createClass({
getInitialState: function() {
return {tiles:[]};
},
componentDidMount: function() {
var PATH = cordova.file.externalRootDirectory + 'testdir/'; //Is called before onDeviceReady
},
render: function() {
return (
<div>
<Navigation title="Dashboard"/>
<Dashboard tiles={this.state.tiles}/>
</div>
);
}
});
index.html:
<body>
<!-- fixed top navbar -->
<div id="app">
</div>
<!-- Dashboard -->
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="bower_components/react/react.js"></script>
<script type="text/javascript" src="bower_components/react/react-dom.js"></script>
<script type="text/javascript" src="js/browser.min.js"></script>
<script type="text/babel" src="js/app.js"></script>
</body>
The error message from the console are:
Uncaught TypeError: Cannot read property 'externalRootDirectory' of undefined ...
on ready
How can I load my React Components after or in onDeviceReady
?
Thanks & Greets, mybecks
In my case, i was waiting for the device information.
Take a look at this link here too.
Following this link, i came up with this code:
function initApp () {
ReactDOM.render(<App />, document.getElementById('root'));
};
if (window.cordova) {
document.addEventListener("deviceready", () => {
initApp();
}, false);
} else {
initApp();
}
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