Christian Lopez
Christian Lopez

Reputation: 218

Can't return JSX with Geolocation coordinates in React

I am trying to display my current location using the Geolocation API. I am trying to do this by returning the data in a method and calling that method inside of the return in render(). The problem is it is not displaying anything.

I know that I can return JSX because, something like this works:

test = () => {
        return (
            <h1>Hello World</h1>
        )
    }

 render(){
        return(
            <div>
                {this.test()}
            </div>
        )
    } 

But when I try this nothing ends up rendering to the page:

currentLocation = () => {
    return navigator.geolocation.getCurrentPosition(position => {
            return (
                <div>
                    <h1>Current Position:</h1>
                    <p>Latitude: {position.coords.latitude}</p>
                    <p>Longitude: {position.coords.longitude}</p>
                </div>
            )
        })
}

    render(){
        return(
            <div>
                {this.currentLocation()}
            </div>
        )
    }

Upvotes: 1

Views: 775

Answers (2)

Chigo Kawa
Chigo Kawa

Reputation: 137

works for me.

     getUserCurrentLocation = () => {
    navigator.geolocation.getCurrentPosition(
      position => {
        this.setState(state => {
          return {
            ...state,
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
        });
      },
      err => console.log(err)
    );
  };

  componentWillMount() {
    // get user location
    this.getUserCurrentLocation();
  }

Upvotes: 0

Long TM
Long TM

Reputation: 113

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      lat: null,
      lng: null,
    }
  }
  componentWillMount() {

    navigator.geolocation.getCurrentPosition(position => {
      this.setState({ lat: position.coords.latitude, lng: position.coords.longitude });
    }, err => console.log(err)
    );
  }

  render() {

    return (
      <div >
        <h1>Current Position:</h1>
        <p>Latitude: {this.state.lat}</p>
        <p>Longitude: {this.state.lng}</p>
      </div>
    );
  }
}

Upvotes: 1

Related Questions