Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I auto-focus a mapbox-gl react geocoder

We are using the React's wrapper to Mapbox geocoder component. Our code is essentially the one in the README, except that we show the geocoder entry field only on request (when clicking some "Edit Address" button).

Is it possible to auto-focus the "Search..." <input/> field (created by the <Geocoder />) component, so that a user can start typing right after the geocoder shows up?

like image 376
herchu Avatar asked Apr 22 '26 23:04

herchu


1 Answers

You should use the Geocoders onInit prop which will be passed a gecoder instance and will be called when the geocoder has been initialized.

class App extends Component {
  state = {
    viewport: {
      width: 400,
      height: 400,
      latitude: 37.7577,
      longitude: -122.4376,
      zoom: 8,
    },
    searchResultLayer: null,
  };

  // rest of the code

  handleGeocoderInit = (geocoderInstance) => {
    const inputEl = geocoderInstance._inputEl;
    inputEl.focus();
  };

  render() {
    const { viewport, searchResultLayer } = this.state;

    return (
      <MapGL
        ref={this.mapRef}
        {...viewport}
        onViewportChange={this.handleViewportChange}
        mapboxApiAccessToken={MAPBOX_TOKEN}>
        <Geocoder
          mapRef={this.mapRef}
          onResult={this.handleOnResult}
          onViewportChange={this.handleGeocoderViewportChange}
          mapboxApiAccessToken={MAPBOX_TOKEN}
          position="top-left"
          onInit={this.handleGeocoderInit}
        />
        <DeckGL {...viewport} layers={[searchResultLayer]} />
      </MapGL>
    );
  }
}

render(<App />, document.getElementById('root'));
like image 111
Murli Prajapati Avatar answered Apr 29 '26 02:04

Murli Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!