N
N
nickname133842020-05-29 11:21:14
JavaScript
nickname13384, 2020-05-29 11:21:14

How to make an autocomplete field with Yandex Maps api?

I am making a Yandex map with a separate input for street search (map and input separately)
for react I use this
I don’t understand how to connect Yandex api to the autocomplete input.
for hints for javascript there is SuggestView, but for react how to connect?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew Ghostuhin, 2020-05-29
@nickname13384

nickname13384

import React, { useState, useRef } from 'react'
import { withYMaps } from 'react-yandex-maps'
import { Column, Layout } from '@ui/layout'
import { ContentLight } from '@ui/dropdown'
import { Input } from '@ui/input'
import styled from '@emotion/styled'
import OnOutsideClick from '@ui/layer/src/OnOutsideClick'
import Dropdown from './Dropdown'
import SuggestView from './SuggestView'
import { update, change, select } from './handlers'
import { SuggestProps } from './types'

const Wrapper = styled('div')({
  position: 'relative',
  width: '100%',
})

const Suggest = ({
  color,
  disabled,
  id,
  readOnly,
  placeholder,
  value,
  ymaps,
  onChange,
  onSuggest,
}: SuggestProps) => {
  const [items, setItems] = useState([])
  const [toggle, setToggle] = useState(false)
  const suggestRef = useRef()
  const onUpdate = update(ymaps, setItems)
  const content = []
  content.push(
    <Input
      id={id}
      key='smart-input'
      disabled={disabled}
      value={value}
      onChange={
        disabled ? null : targetValue => change(targetValue, onUpdate, onChange)
      }
      color={color}
      readOnly={readOnly}
      placeholder={placeholder}
      onClick={() => setToggle(true)}
    />,
  )

  if (
    toggle &&
    items.length > 0 &&
    !(items[0] !== value && items.length === 1)
  ) {
    content.push(
      <OnOutsideClick
        key='smart-suggest'
        target={suggestRef.current}
        onOutsideClick={() => setToggle(false)}
      >
        <Dropdown>
          <ContentLight borderRadius='s' width='large' noPopup>
            <Column>
              <Layout basis='12px' />
              {items.map(s => (
                <SuggestView
                  key={Math.random()}
                  onClick={() =>
                    select(s.value, onSuggest, onUpdate, onChange, setToggle)
                  }
                >
                  {s.displayName}
                </SuggestView>
              ))}
              <Layout basis='12px' />
            </Column>
          </ContentLight>
        </Dropdown>
      </OnOutsideClick>,
    )
  }

  return <Wrapper ref={suggestRef}>{content}</Wrapper>
}

M
mt. NATS, 2020-05-29
@Dimastik86

javascript autocomplete react

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question