Reputation: 5021
In my one of react component,
import React, { Component } from 'react';
import './css/addItem.css';
class AddItem extends Component {
constructor(props) {
super(props);
}
showPosition(position) {
console.log("Latitude: ",position.coords.latitude+
" Longitude: ",position.coords.longitude);
}
getGeoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
render() {
return (
<div>
.....
.....
<button onClick={this.getGeoLocation}>Get GeoLocation</button>
</div>
);
}
}
export default AddItem;
My it says Cannot read property 'showPosition' of undefined
.
GeoLocation is simply not working
.
Being new to React, I tried,
this.showPosition = this.showPosition.bind(this);
in constructor.
But that did not help.
Could some one please explain what am I doing wrong and how to fix it ?
Upvotes: 2
Views: 117
Reputation: 2272
Your function getGeoLocation
is called with another context. React does not bind your event listeners or any another function automatically. So you receive this === undefined
in getGeoLocation
. To fix this issue, you could use this.getGeoLocation = this.getGeoLocation.bind(this)
in your constructor function, or just use class properties with an arrow function. For example:
import React, { Component } from 'react';
import './css/addItem.css';
class AddItem extends Component {
constructor(props) {
super(props);
}
showPosition(position) {
console.log("Latitude: ",position.coords.latitude+
" Longitude: ",position.coords.longitude);
}
// We use class property with arrow function to bind context:
getGeoLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
render() {
return (
<div>
.....
.....
<button onClick={this.getGeoLocation}>Get GeoLocation</button>
</div>
);
}
}
export default AddItem;
Upvotes: 2