D.B.
D.B.

Reputation: 99

Cannot read properties of undefined (reading 'props')

In my react JS web app. I am getting below error from the following code.

This code is taken from:

https://www.npmjs.com/package/google-maps-react

import React from "react";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from 'google-maps-react';

const Googlemap = () => {
        return (
                <Map google={this.props.google} zoom={14}>
                        <Marker onClick={this.onMarkerClick}
                                name={'Current location'} />
                        <InfoWindow onClose={this.onInfoWindowClose}>
                                <div>
                                        <h1>{this.state.selectedPlace.name}</h1>

                                </div>
                        </InfoWindow>
                </Map>
        );
}
export default GoogleApiWrapper({
        apiKey: ("MY KEY")
})(Googlemap)

enter image description here

Please advise

Regards

Upvotes: 1

Views: 1529

Answers (1)

thisisrandy
thisisrandy

Reputation: 3065

In the sample page you provide, the following code is presented:

import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
 
export class MapContainer extends Component {
  render() {
    return (
      <Map google={this.props.google} zoom={14}>
 
        <Marker onClick={this.onMarkerClick}
                name={'Current location'} />
 
        <InfoWindow onClose={this.onInfoWindowClose}>
            <div>
              <h1>{this.state.selectedPlace.name}</h1>
            </div>
        </InfoWindow>
      </Map>
    );
  }
}
 
export default GoogleApiWrapper({
  apiKey: (YOUR_GOOGLE_API_KEY_GOES_HERE)
})(MapContainer)

Notice that MapContainer is a class which extends Component, which is why this.props is a valid reference.

In your code, you use the functional style of defining MapContainer (you use the name Googlemap), which is valid, but needs to be handled a little bit differently. As other users have pointed out, you need to explicitly parameterize const Googlemap = (props) => ... or destructure as in const Googlemap = ({google, ...props}) => ... and then use props (or google in the destructured version) explicitly instead of this.props.

However, it appears that GoogleApiWrapper is providing some other things, e.g. onMarkerClick and onInfoWindowClose, so you're probably a lot better off following their example and using the old Component class style instead of the new functional style for your component.

Upvotes: 1

Related Questions