Search code examples
javascriptreactjsjsxreact-state-managementreact-state

Unable to pass state value through react jsx. Getting error - Unexpected token : 'this'


The following code initializes state keys as NULL and assigns them certain values on mounting of components. (All this is working fine)

The problem is in accessing these state values in the render function. In Map Component, initialCenter attribute takes an object as value. This where I am passing the state value and getting the following error.

Failed to compile ./src/components/Mapcontainer.js Line 32:21: Parsing error: Unexpected keyword 'this'

export class MapContainer extends Component {
  constructor() {
    super();
    this.state = {
      lat: null,
      lng: null,
    };
  }
  componentDidMount() {
    navigator.geolocation.watchPosition((position) => {
      this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
    });
  }
  render() {
    return (
      <Map
        google={this.props.google}
        zoom={14}
        style={mapStyles}
        initialCenter={{
          lat: {this.state.lat},
          lng: {this.state.lng},
        }}
      >
      <Marker />
      </Map>
    );
  }
}

Solution

  • initialCenter={{
       lat: {this.state.lat},
       lng: {this.state.lng},
    }}
    

    should be

    initialCenter={this.state} 
    

    or

    initialCenter={{
       lat: this.state.lat,
       lng: this.state.lng
    }}
    

    because you'll have nested objects in the prior case. And lat: {this.state.lat} will cause a syntax error because {this.state.lat} will result in an object without a key.