I'm trying to use the sensor's API with react and I can't seen to be able to make it work.
It gives me an error saying that AmbientLightSensor (in my case this sensor) is undefined
If I run the script outside react ( more exactly with an extension from VSCode "live server" ) it works fine ( just a html with some JS code in it ). That's cool and all but in this case at least I want to run this script inside react and it just doesn't let me.
So far I've tried:
running this code in react as a class method called by componentDidMount and that (Simply i've put my JS code in there ^^ )
running this code with the tag hoping that maybe react isn't really using the JS that I know and that maybe running it inside html will change this ... No it didn't do the trick So at this point I'm unsure what to even check to make this work
Here is my code, the js code I'm trying to run is inside the Did mount component
class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const details = document.getElementById("details");
// Feature detection
if (window.AmbientLightSensor) {
try {
const sensor = new AmbientLightSensor();
// Detect changes in the light
sensor.onreading = () => {
details.innerHTML = sensor.illuminance;
// Read the light levels in lux
// < 50 is dark room
if (sensor.illuminance < 50) {
document.body.className = "darkLight";
} else {
document.body.className = "brightLight";
}
};
// Has an error occured?
sensor.onerror = event =>
(document.getElementById("details").innerHTML =
event.error.message);
sensor.start();
} catch (err) {
details.innerHTML = err.message;
}
} else {
details.innerHTML =
"It looks like your browser doesnt support this feature";
}
}
render() {
return (
Ambient Light Sensor
Current Light Levels
);
}
}
And also here is the working html
Ambient Light Sensor
Ambient Light Sensor
Current Light Levels
const details = document.getElementById("details");
// Feature detection
if (window.AmbientLightSensor) {
try {
const sensor = new AmbientLightSensor();
// Detect changes in the light
sensor.onreading = () => {
details.innerHTML = sensor.illuminance;
// Read the light levels in lux
// < 50 is dark room
if (sensor.illuminance < 50) {
document.body.className = "darkLight";
} else {
document.body.className = "brightLight";
}
};
// Has an error occured?
sensor.onerror = event =>
(document.getElementById("details").innerHTML =
event.error.message);
sensor.start();
} catch (err) {
details.innerHTML = err.message;
}
} else {
details.innerHTML =
"It looks like your browser doesnt support this feature";
}
```
PS* for this to work you need to run this on a https server
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)