Keyboard Navigation

The Navigator API is used to redirect users when a suggestion link is opened programmatically using keyboard navigation.

This API defines how a URL should be opened with different key modifiers:

  • In the current tab triggered on Enter
  • In a new tab triggered on ⌘ Enter or Ctrl Enter
  • In a new window triggered on ⇧ Enter
important

To activate keyboard navigation, use getSuggestionUrl in your source to provide the value to process as a URL. This indicates the navigator API which links to open on Enter.

Example

const autocomplete = createAutocomplete({
// ...
getSources() {
return [
{
getSuggestionUrl({ suggestion }) {
return suggestion.url;
},
getSuggestions() {
return [];
},
},
];
},
// Default navigator values
navigator: {
navigate({ suggestionUrl }) {
window.location.assign(suggestionUrl);
},
navigateNewTab({ suggestionUrl }) {
const windowReference = window.open(suggestionUrl, '_blank', 'noopener');
if (windowReference) {
windowReference.focus();
}
},
navigateNewWindow({ suggestionUrl }) {
window.open(suggestionUrl, '_blank', 'noopener');
},
},
});

If you use autocomplete in a Gatsby website, you can leverage their navigate API to avoid hard refreshes.

import { navigate } from 'gatsby';
const autocomplete = createAutocomplete({
navigator: {
navigate({ suggestionUrl }) {
navigate(suggestionUrl);
},
},
});

Reference

Params

The provided params get merged with the default configuration so that you don't have to rewrite all methods.

navigate

(params: { suggestionUrl: string, suggestion: TItem, state: AutocompleteState<TItem> }) => void

Function called when a URL should be open in the current page.

This is triggered on Enter

navigateNewTab

(params: { suggestionUrl: string, suggestion: TItem, state: AutocompleteState<TItem> }) => void

Function called when a URL should be open in a new tab.

This is triggered on Cmd Enter or Ctrl Enter

navigateNewWindow

(params: { suggestionUrl: string, suggestion: TItem, state: AutocompleteState<TItem> }) => void

Function called when a URL should be open in a new window.

This is triggered on Shift Enter