question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Adding a new method to GoogleAutoComplete.js to autofill input

See original GitHub issue

After studying how the functions/methods were defined in GoogleAutoComplete.js:

_this._clearSearchs = function () {
    if (_this._isMounted) {
        _this.setState({
            locationResults: [],
        });
    }
};

I attempted to write one to get the text input inside <GoogleAutoComplete> to autocomplete when one of the search results was selected:

Customised LocationItem.js to only render the <View> component child:

class LocationItem extends PureComponent {
    render () {
        return (
            <View style={styles.root}>
                    <Text>{this.props.description}</Text>
            </View>
        );
    }
}

Moved <TouchableOpacity> to the locationResults.map in the App.js instead to call the handleTextAutoFill nested inside <GoogleAutoComplete>

<GoogleAutoComplete apiKey={'API_KEY'}>
{({handleTextChange, locationResults, clearSearchs, handleTextAutoFill}) => (
    <React.Fragment>
        <View style={{marginTop: 80}}>
            <TextInput
            style={{height: 40, paddingHorizontal: 10, marginHorizontal: 20}}
            placeholder={'Search a place'}
            onChangeText={handleTextChange}
            />
        </View>
        <ScrollView>
            {locationResults.map(el => (
                <TouchableOpacity onPress={() => handleTextAutoFill(el.description)} >
                    <LocationItem
                        {...el}
                        key={el.id}
                    />
                </TouchableOpacity>
            ))}
        </ScrollView>
    </React.Fragment>
)}
</GoogleAutoComplete>

The handleTextAutoFill function written inside of GoogleAutoComplete.js, inserted after the _this._handleTextChange:

 //after selection has been made, the list of search results will be emptied
_this._handleTextAutoFill = function (selectedResult){
    _this.setState({
        textInput: selectedResult,
        locationResults: [],
    });
 };

However when I select a result nothing happens. I’m not very familiar with the ReactJS syntax so I think my onPress={() => handleTextAutoFill(el.description)} is incorrect.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:17 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
Teallycommented, Aug 20, 2018

Alright, after thinking about it long and hard, the solution I came up with involves customising a <TextInput/> so that you can parse both parent and superparent .setState() functions into it via custom props.

class CustomTextInput extends Component {
    textChange = (inputValue) => {
        this.props.gacHandle(inputValue); // these two seperate functions
        this.props.formHandle(inputValue); // can be linked and called simultaneously by onChangeText
    }

    render(){
        return (
            <TextInput
            style={this.props.style}
            placeholder={this.props.placeholder}
            onChangeText={this.textChange}
            value={this.props.value}
            />
        );
    }
}

====== Usage:

class App extends Component {
    state = {
        autoCompleteValue: null,
    };

    onAutoCompleteInput = autoCompleteValue => {
        this.setState({ inputValue: autoCompleteValue });
    };
    render(){
        return (
            <TouchableWithoutFeedback style={{paddingHorizontal: 20, backgroundColor: '#999'}} onPress={Keyboard.dismiss}>
                <GoogleAutoComplete apiKey={'API_KEY'}>
                {({handleTextChange, locationResults, clearSearchs}) => (
                    <React.Fragment>
                        <View style={{marginTop: 80}}>
                            <CustomTextInput
                                style={{height: 40, paddingHorizontal: 10, marginHorizontal: 20}}
                                placeholder={'Search a place'}
                                gacHandle={handleTextChange} // parse the functions you want to call
                                formHandle={this.onAutoCompleteInput} // under these two, declare more props if needed
                                value={this.state.inputValue}
                            />
.
.
.

This issue wasn’t really related to your repo, but I appreciate the help anyways.

1reaction
EQuimpercommented, Aug 14, 2018

Ok so I make it work. This can’t be a feature cause I want it to be flexible so this is something really easy to add. Took me like 5 lines.

First if we follow my example I will do this


export default class App extends React.Component {
  state = {
    autoCompleteValue: null,
  };

  onAutoCompleteInput = autoCompleteValue => {
    this.setState({ autoCompleteValue });
  };

  render() {
    return (
      <UtilityThemeProvider>
        <GoogleAutoComplete
          apiKey={API_KEY}
          debounce={500}
          minLength={3}
          components="country:ca"
        >
          {({
            handleTextChange,
            locationResults,
            fetchDetails,
            isSearching,
            inputValue,
            clearSearchs,
          }) => (
            <React.Fragment>
              <View style={styles.inputWrapper}>
                <TextInput
                  style={styles.textInput}
                  placeholder="Search a places"
                  onChangeText={handleTextChange}
                  value={this.state.autoCompleteValue || inputValue}
                />
                <Button title="Clear" onPress={clearSearchs} />
              </View>
              {isSearching && <ActivityIndicator size="large" color="red" />}
              <ScrollView>
                {locationResults.map(el => (
                  <LocationItem
                    {...el}
                    key={el.id}
                    onAutoCompleteInput={this.onAutoCompleteInput}
                    fetchDetails={fetchDetails}
                  />
                ))}
              </ScrollView>
            </React.Fragment>
          )}
        </GoogleAutoComplete>
      </UtilityThemeProvider>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  textInput: {
    height: 40,
    width: 300,
    borderWidth: 1,
    paddingHorizontal: 16,
  },
  inputWrapper: {
    marginTop: 80,
    flexDirection: 'row',
  },
});

And for the locationItem

class LocationItem extends React.PureComponent {
  _handlePress = async () => {
    this.props.onAutoCompleteInput(this.props.description);
    const res = await this.props.fetchDetails(this.props.place_id);
    console.log('result', res);
  };

  render() {
    return (
      <TouchableOpacity style={styles.root} onPress={this._handlePress}>
        <Text>{this.props.description}</Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  root: {
    height: 40,
    borderBottomWidth: StyleSheet.hairlineWidth,
    justifyContent: 'center',
  },
});

export default LocationItem;
Read more comments on GitHub >

github_iconTop Results From Across the Web

Place Autocomplete | Maps JavaScript API - Google Developers
Autocomplete adds a text input field to your web page, and monitors that field for character entries. As the user enters text, autocomplete...
Read more >
How can I add google autocomplete at multiple input box on ...
I have found a code for autocomplete address on google side.. where they only link with one input box. But I want to...
Read more >
How to use Place Autocomplete to auto-fill forms - YouTube
Turn your address form input field into an address autocomplete bar. Place Autocomplete can help you provide a better checkout experience ...
Read more >
Autocomplete Field on Google Web App - YouTube
In this video, I demonstrate how to use the JQuery Autocomplete Field within a Bootstrap Form on Google Web App. Video, Code, ...
Read more >
Add Google Places Autocomplete To An Input Field - YouTube
By the end of this video, you'll be able to enable/ add Google Places Autocomplete functionality to an input field that will show...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found