Skip to Content
dk-address

Hooks

Read the address field's state, or run the address search under your own UI.

HookUse it toRenders
useAddressInput()Read and act on the state of an <AddressInput> from inside itNothing; needs <AddressInput> around it
useAddressAutosuggest()Run the address search with your own input, or another library's autocompleteNothing; works on its own

Both come from @dk-address/react.

useAddressInput

import { AddressInput, useAddressInput } from "@dk-address/react";

function SelectedAddress() {
  const { state } = useAddressInput();
  if (state.selection?.status !== "success") return null;
  return <p>{state.selection.details?.label}</p>;
}

<AddressInput>
  {/* …parts… */}
  <SelectedAddress />
</AddressInput>;

Call it in any component inside <AddressInput>; outside, it throws. It returns:

Field
stateThe store state: text, caret, slot, suggestions, status, selection
select(suggestion)Pick a suggestion, as if it was clicked
selectById(id)Prefill from a stored address id; fills the text without opening the list or taking focus
clear()Empty the field and the selection

Typical uses are a hidden form input with the selected id, a hint while a gap is empty, and prefilling an edit form. The Styling AddressInput guide shows each.

useAddressAutosuggest

import { suggestionKey, useAddressAutosuggest } from "@dk-address/react";

function MyAddressField() {
  const { state, store, inputRef } = useAddressAutosuggest({ kind: "address" });
  return (
    <>
      <input
        ref={inputRef}
        value={state.value}
        onChange={(event) => store.setInput(event.target.value)}
      />
      {state.suggestions.map((suggestion) => (
        <button
          key={suggestionKey(suggestion)}
          type="button"
          // Keep focus in the input, so the caret can move into the gap after the pick.
          onMouseDown={(event) => event.preventDefault()}
          onClick={() => store.select(suggestion)}
        >
          {suggestion.label}
        </button>
      ))}
    </>
  );
}

It takes the same options as <AddressInput> and returns:

Field
stateThe store state
storeThe store: setInput(text) on typing, select(suggestion) on a pick, setOpen(open), selectById(id), clear()
inputRefAttach it to the real <input>, so the caret moves into the gap after a pick. It only moves while the input has focus, so keep focus there when a suggestion is clicked

It adds no ARIA, keyboard handling or popup: your component provides those. That makes it the hook for wiring another library's autocomplete; the Component libraries guide maps the store onto typical autocomplete props, and the Ant Design block is a complete example. For the bare <input> above, add the combobox ARIA yourself, or use <AddressInput>.

A new client option is used from the next search on; changing it doesn't search again, so creating the client inline is safe.