Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs Component is rendered before cordovas onDeviceReady function

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

like image 818
mybecks Avatar asked Nov 10 '22 02:11

mybecks


1 Answers

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();
}
like image 111
Igor Phelype Guimarães Avatar answered Nov 14 '22 21:11

Igor Phelype Guimarães