Material-ui - Google Autocomplete Address

I am using Material-Ui in a React application and I am trying to add Google input autocomplete for addresses in my form.

Here is my problem, I found this library https://github.com/ErrorPro/react-google-autocomplete , which integrates google maps API for places, but the input looks like the most basic input, i.e. with 0 style.

Now my code is as follows:

<Autocomplete
onPlaceSelected={(place) => {
    console.log("Place selected", place);
}}
types={['address']}
/>

This code works fine and prints the address, the simple problem is that the input has a default appearance, and I want it to have ui stuff.

I also looked at this https://github.com/ydeshayes/googlePlaceAutocomplete library , which seems to be exactly what I want, but I can't get it to work and it seems to be little documented. So I tried to write code like this:

<GooglePlaceAutocomplete 
    onChange={this.onAutoCompleteInputChangeFct.bind(this)}
    onNewRequest={this.onClickLocationFct.bind(this)}
    name={'location'}
/>

But with this code I have my own contribution, but when I type sentences in it, it seems that it does not work.

So my question is: is there a way to wrap an AutoComplete component in a TextField element from material-ui?

+4
source share
1 answer

, <input /> DOM, TextField, componentDidMount() google.maps.new places.Autocomplete() . Autocomplete place_changed - , , Redux /, (, onPlaceChanged)

jsFiddle CSS, . , API Google- : https://jsfiddle.net/e0jboqdj/3/

class LocationSearchBox extends React.Component {
  componentDidMount() {
    if (typeof google === 'undefined') {
      console.warn('Google Places was not initialized. LocationSearchBox will not function.');
      return;
    }

    const { country, onPlaceChanged } = this.props;
    const { places } = google.maps;

    let options;

    if (country) {
      options = {
        componentRestrictions: { country }
      };
    }

    const input = this.locationSearch;

    input.setAttribute('placeholder', '');

    if (!input._autocomplete) {
      input._autocomplete = new places.Autocomplete(input, options);

      input._autocomplete.addListener('place_changed', () => {
        onPlaceChanged && onPlaceChanged(input._autocomplete.getPlace());
      }.bind(input._autocomplete));
    }
  }

  render() {
    return (
      <span>
        <TextField ref={ref => (this.locationSearch = ref.input)} hintText="Search nearby" />
      </span>
    );
  }
}
+1

Source: https://habr.com/ru/post/1663360/


All Articles