Search code examples
javascriptreactjsinputgoogle-places-apigoogle-places-autocomplete

How to check if <InputB /> has a value after a value for <InputA /> has been selected?


I have the two following input components:

function Inputs() {
  return (      
    <div>
      <GooglePlacesAutocomplete
        onSelect={(data) => getPointA(data)}
        placeholder="Enter place or address for Point A"
      />

      <GooglePlacesAutocomplete
        onSelect={(data) => getPointB(data)}
        placeholder="Enter place or address for Point B"
        idPrefix="pointB"
      />
    </div>
  )
}

When I select a value from the first GooglePlacesAutocomplete component, I want to check if the second GooglePlacesAutocomplete component has a value. How can I do this? Here is a link to the component I'm using: https://www.npmjs.com/package/react-google-places-autocomplete

Thanks!


Solution

  • You can store the state of your selected values in you Inputs component so you have access to the selected values:

    function Inputs() {
      const [placeA, setPlaceA] = useState('');
      const [placeB, setPlaceB] = useState('');
      const getPointA = (data) => {
        setPlaceA(data)
      }
      const getPointB = (data) => {
        setPlaceB(data)
      }
      return (      
        <div>
          <GooglePlacesAutocomplete
            onSelect={(data) => getPointA(data)}
            placeholder="Enter place or address for Point A"
          />
    
          <GooglePlacesAutocomplete
            onSelect={(data) => getPointB(data)}
            placeholder="Enter place or address for Point B"
            idPrefix="pointB"
          />
        </div>
      )
    }