1+ /* global document */
12import PropTypes from "prop-types"
23import React from "react"
34import styled from "styled-components"
@@ -20,10 +21,19 @@ class GooglePlacesSuggest extends React.Component {
2021 }
2122
2223 this . handleKeyDown = this . handleKeyDown . bind ( this )
24+ this . onFocusChange = this . onFocusChange . bind ( this )
25+ this . handleDOMClick = this . handleDOMClick . bind ( this )
2326 }
2427
28+ hasFocus = false
29+
2530 componentWillMount ( ) {
2631 this . updatePredictions ( this . props . autocompletionRequest )
32+ document . addEventListener ( "click" , this . handleDOMClick )
33+ }
34+
35+ componentWillUnmount ( ) {
36+ document . removeEventListener ( "click" , this . handleDOMClick )
2737 }
2838
2939 componentWillReceiveProps ( nextProps ) {
@@ -43,6 +53,7 @@ class GooglePlacesSuggest extends React.Component {
4353 predictions : [ ] ,
4454 } ,
4555 ( ) => {
56+ this . hasFocus = false
4657 this . geocodePrediction ( suggest . description , result => {
4758 onSelectSuggest ( result , suggest )
4859 } )
@@ -54,7 +65,13 @@ class GooglePlacesSuggest extends React.Component {
5465 const { googleMaps} = this . props
5566 const autocompleteService = new googleMaps . places . AutocompleteService ( )
5667 if ( ! autocompletionRequest || ! autocompletionRequest . input ) {
57- this . setState ( { open : false , predictions : [ ] } )
68+ this . setState (
69+ {
70+ open : false ,
71+ predictions : [ ] ,
72+ } ,
73+ ( ) => ( this . hasFocus = false )
74+ )
5875 return
5976 }
6077
@@ -115,6 +132,16 @@ class GooglePlacesSuggest extends React.Component {
115132 this . setState ( { focusedPredictionIndex : index } )
116133 }
117134
135+ onFocusChange ( val ) {
136+ this . hasFocus = val
137+ }
138+
139+ handleDOMClick ( ) {
140+ if ( ! this . hasFocus && this . state . open ) {
141+ this . setState ( { open : false } )
142+ }
143+ }
144+
118145 render ( ) {
119146 const { focusedPredictionIndex, open, predictions} = this . state
120147 const {
@@ -134,6 +161,7 @@ class GooglePlacesSuggest extends React.Component {
134161 customRender = { customRender }
135162 onSelect = { suggest => this . handleSelectPrediction ( suggest ) }
136163 textNoResults = { textNoResults }
164+ onFocusChange = { this . onFocusChange }
137165 />
138166 ) }
139167 </ Wrapper >
0 commit comments