Reputation: 2853
I have loaded a library (cordova) in my main index.html file. Then I added the eventlistener 'deviceready' on my document. Now how can I call this function and the related library inside a react component?
Html file:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<div id="app"></div>
</body>
<script type="text/javascript" src="cordova.js"></script>
<script>
document.addEventListener('deviceready', onDeviceReady);
// this is the function I want to call inside my component.
// function onDeviceReady() {
// var rect = { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight };
// cordova.plugins.camerapreview.startCamera(rect, 'back', true, true, true)
// cordova.plugins.camerapreview.show();
// }
</script>
</html>
My react component:
import React, { Component } from 'react';
class Example extends Component {
// Here I want to call my cordova actions inside the eventlistener
render() {
return (
<div>
<p>Example</p>
</div>
);
}
}
export default Example;
Upvotes: 0
Views: 237
Reputation: 4080
By using Reacjs lifesycle is a proper way to add and remove events
So you can do something like this:
import React, { Component } from 'react';
class Example extends Component {
componentDidMount() {
document.addEventListener('deviceready', this.deviceReady);
}
componentWillUnmount() {
document.removeEventListener('deviceready', this.deviceReady);
}
deviceReady () {
// Do some stuff
}
render() {
return (
<div>
<p>Example</p>
</div>
);
}
}
export default Example;
Upvotes: 2