svelte-typeahead

nstallation

Yarn

yarn add -D svelte-typeahead

NPM

npm i -D svelte-typeahead

pnpm

pnpm i -D svelte-typeahead

Usage

SvelteKit set-up

To use this component with SvelteKit or vite-powered set-ups, instruct vite to optimize "fuzzy" in your configuration.

// svelte.config.js
const config = {
  kit: {
    target: "#svelte",
    vite: {
      optimizeDeps: {
        include: ["fuzzy"],
      },
    },
  },
};

Styling

Note: this component is minimally styled by design. You can target the component using the [data-svelte-typeahead] selector.

:global([data-svelte-typeahead]) {
  margin: 1rem;
}

Basic

Pass an array of objects to the data prop. Use the extractor prop to specify the value to search on.

<script>
  import Typeahead from "svelte-typeahead";

  const data = [
    { state: "California" },
    { state: "North Carolina" },
    { state: "North Dakota" },
    { state: "South Carolina" },
    { state: "South Dakota" },
    { state: "Michigan" },
    { state: "Tennessee" },
    { state: "Nevada" },
    { state: "New Hampshire" },
    { state: "New Jersey" },
  ];

  const extract = (item) => item.state;
</script>

<Typeahead {data} {extract} />

Custom-styled results

This component uses the fuzzy library to highlight matching characters with the mark element.

Override the default slot to render custom results.

<Typeahead {data} {extract} let:result let:index>
  <div style="color: red; font-weight: bold;">
    {@html result.string}
    {index}
  </div>
</Typeahead>

No results

Use the “no-results” slot to render a message if the search value does not yield results.

<Typeahead value="abcd" {data} {extract} let:value>
  <svelte:fragment slot="no-results">
    No results found for "{value}"
  </svelte:fragment>
</Typeahead>

Limit the number of results

Use the limit prop to specify the maximum number of results to display. The default is Infinity.

<Typeahead limit={2} {data} {extract} />

Disabled items

Disable items using the disable filter.

In the following example, items with a state value containing “Carolina” are disabled. Disabled items are not selectable nor keyboard navigable.

<Typeahead
  {data}
  value="ca"
  extract={(item) => item.state}
  disable={(item) => /Carolina/.test(item.state)}
/>

Focus after select

Set focusAfterSelect to true to re-focus the search input after selecting a result.

<Typeahead focusAfterSelect {data} {extract} />

Leave a comment

Your email address will not be published. Required fields are marked *