Search code examples
reactjsgoogle-mapsinputgoogle-maps-api-3react-state-management

How to get the state updated of input field of google map api in React app


According to the official docs of google map api, I was trying to implement the autocomplete search input in my React app as per the following:

import React, { Component } from 'react';

export class App extends Component {
    state = {
        location: ''
    };

    handleChange = (e) => {
        this.setState({ location: e.target.value });
    };
    render() {
        function initAutocomplete() {
            var input = document.getElementById('pac-input');
            var searchBox = new window.google.maps.places.SearchBox(input);
        }
        initAutocomplete();
        return (
            <input
                defaultValue={this.state.location}
                onChange={this.handleChange}
                id="pac-input"
                className="controls"
                type="text"
                placeholder="Search your College"
            />
        );
    }
}

export default App;

and I managed to get it to work properly. But, the only problem that I'm seeing that whenever I select/click the autocomplete option, the value of the input bar gets updated with the selected address but not in the state. You can check out this short video demo and please suggest me what changes should I do to get the state management working correctly?


Solution

  • The problem here is that you're listening to the input's onChange event only, not the Autocomplete's places_changed event, so the input's onChange function doesn't run when you select a place from the autocomplete list of place suggestions. Try amending your code as follows:

    import React, { Component } from "react";
    
    export class App extends Component {
      state = {
        location: ""
      };
    
      componentDidMount() {
        const app = this;
        function initAutocomplete() {
          var input = document.getElementById("pac-input");
          var searchBox = new window.google.maps.places.SearchBox(input);
          searchBox.addListener("places_changed", function() {
            app.setState({ location: document.getElementById("pac-input").value });
          });
        }
        initAutocomplete();
      }
    
      handleChange = e => {
        this.setState({ location: e.target.value });
      };
    
      render() {
        return (
          <input
            defaultValue={this.state.location}
            onChange={this.handleChange}
            id="pac-input"
            className="controls"
            type="text"
            placeholder="Search your College"
          />
        );
      }
    }
    
    export default App;