Convert Figma logo to code with AI

rob-balfre logosvelte-select

Svelte Select. A select component for Svelte

1,271
180
1,271
86

Quick Overview

Svelte-select is a customizable select component for Svelte applications. It provides a flexible and feature-rich dropdown selection interface that can be easily integrated into Svelte projects, offering both single and multi-select capabilities.

Pros

  • Highly customizable with numerous configuration options
  • Supports both single and multi-select functionality
  • Includes features like keyboard navigation, grouping, and filtering
  • Actively maintained with regular updates and improvements

Cons

  • Learning curve for advanced customization
  • May be overkill for simple select needs
  • Some users report occasional performance issues with large datasets
  • Documentation could be more comprehensive for complex use cases

Code Examples

  1. Basic usage:
<script>
  import Select from 'svelte-select';
  
  let items = [
    {value: 1, label: 'One'},
    {value: 2, label: 'Two'},
    {value: 3, label: 'Three'}
  ];
</script>

<Select {items} />
  1. Multi-select with custom item component:
<script>
  import Select from 'svelte-select';
  import CustomItem from './CustomItem.svelte';
  
  let items = [/* ... */];
</script>

<Select {items} multiple isMulti Item={CustomItem} />
  1. Grouped items with filtering:
<script>
  import Select from 'svelte-select';
  
  let groupedItems = [
    {
      label: 'Fruits',
      items: [{value: 'apple', label: 'Apple'}, {value: 'banana', label: 'Banana'}]
    },
    {
      label: 'Vegetables',
      items: [{value: 'carrot', label: 'Carrot'}, {value: 'broccoli', label: 'Broccoli'}]
    }
  ];
</script>

<Select {groupedItems} groupBy={(item) => item.label} filter={true} />

Getting Started

  1. Install the package:

    npm install svelte-select
    
  2. Import and use in your Svelte component:

    <script>
      import Select from 'svelte-select';
      
      let items = [
        {value: 1, label: 'Option 1'},
        {value: 2, label: 'Option 2'},
        {value: 3, label: 'Option 3'}
      ];
      
      let selectedValue;
    </script>
    
    <Select {items} bind:value={selectedValue} />
    
  3. Customize as needed using the available props and CSS variables.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Svelte Select

Svelte Select

A select/autocomplete/typeahead Svelte component.

Demos

💥 Examples of every prop, event, slot and more 💥

✨ REPL: Simple ✨

💃 REPL: Show me everything 🕺

Installation

npm install svelte-select

Upgrading from Svelte Select v4 to v5 (not to be confused with Svelte v5!)

See migration guide if upgrading from v4 to v5.

Rollup and low/no-build setups

List position and floating is powered by floating-ui, see their package-entry-points docs if you encounter build errors.

Props

PropTypeDefaultDescription
itemsany[][]Array of items available to display / filter
valueanynullSelected value(s)
justValueanynullREAD-ONLY Selected value(s) excluding container object
itemIdstringvalueOverride default identifier
labelstringlabelOverride default label
idstringnullid attr for input field
filterTextstring''Text to filter items by
placeholderstringPlease selectPlaceholder text
hideEmptyStatebooleanfalseWhen no items hide list
listOpenbooleanfalseOpen/close list
classstring''container classes
containerStylesstring''Add inline styles to container
clearablebooleantrueEnable clearing of value(s)
disabledbooleanfalseDisable select
multiplebooleanfalseEnable multi-select
searchablebooleantrueIf false search/filtering is disabled
groupHeaderSelectablebooleanfalseEnable selectable group headers
focusedbooleanfalseControls input focus
listAutoWidthbooleantrueIf false will ignore width of select
showChevronbooleanfalseShow chevron
inputAttributesobject{}Pass in HTML attributes to Select's input
placeholderAlwaysShowbooleanfalseWhen multiple placeholder text will always show
loadingbooleanfalseShows loading-icon. loadOptions will override this
listOffsetnumber5px space between select and list
debounceWaitnumber300milliseconds debounce wait
floatingConfigobject{}Floating UI Config
hasErrorbooleanfalseIf true sets error class and styles
namestringnullName attribute of hidden input, helpful for form actions
requiredbooleanfalseIf Select is within a <form> will restrict form submission
multiFullItemClearablebooleanfalseWhen multiple selected items will clear on click
closeListOnChangebooleantrueAfter on:change list will close
clearFilterTextOnBlurbooleantrueIf false, filterText value is preserved on:blur

Named slots

<Select>
  <div slot="prepend" />
  <div slot="selection" let:selection let:index /> <!-- index only available when multiple -->
  <div slot="clear-icon" />  
  <div slot="multi-clear-icon" />  
  <div slot="loading-icon" />  
  <div slot="chevron-icon" /> 
  <div slot="list-prepend" />  
  <div slot="list" let:filteredItems />  
  <div slot="list-append" />  
  <div slot="item" let:item let:index />  
  <div slot="input-hidden" let:value />
  <div slot="required" let:value />
  <!-- Remember you can also use `svelte:fragment` to avoid a container DOM element. -->
  <svelte:fragment slot="empty" />  
</Select>

Events

Event NameCallbackDescription
change{ detail }fires when the user selects an option
input{ detail }fires when the value has been changed
focus{ detail }fires when select > input on:focus
blur{ detail }fires when select > input on:blur
clear{ detail }fires when clear is invoked or item is removed (by user) from multi select
loaded{ options }fires when loadOptions resolves
error{ type, details }fires when error is caught
filter{ detail }fires when listOpen: true and items are filtered
hoverItem{ detail }fires when hoverItemIndex changes

Items

items can be simple arrays or collections.

<script>
  import Select from 'svelte-select';

  let simple = ['one', 'two', 'three'];

  let collection = [
    { value: 1, label: 'one' },
    { value: 2, label: 'two' },
    { value: 3, label: 'three' },
  ];
</script>

<Select items={simple} />

<Select items={collection} />

They can also be grouped and include non-selectable items.

<script>
  import Select from 'svelte-select';

  const items = [
    {value: 'chocolate', label: 'Chocolate', group: 'Sweet'},
    {value: 'pizza', label: 'Pizza', group: 'Savory'},
    {value: 'cake', label: 'Cake', group: 'Sweet', selectable: false},
    {value: 'chips', label: 'Chips', group: 'Savory'},
    {value: 'ice-cream', label: 'Ice Cream', group: 'Sweet'}
  ];

  const groupBy = (item) => item.group;
</script>

<Select {items} {groupBy} />

You can also use custom collections.

<script>
  import Select from 'svelte-select';

  const itemId = 'id';
  const label = 'title';

  const items = [
    {id: 0, title: 'Foo'},
    {id: 1, title: 'Bar'},
  ];
</script>

<Select {itemId} {label} {items} />

Async Items

To load items asynchronously then loadOptions is the simplest solution. Supply a function that returns a Promise that resolves with a list of items. loadOptions has debounce baked in and fires each time filterText is updated.

<script>
  import Select from 'svelte-select';

  import { someApiCall } from './services';

  async function examplePromise(filterText) {
    // Put your async code here...
    // For example call an API using filterText as your search params
    // When your API responds resolve your Promise
    let res = await someApiCall(filterText);
    return res;
  }
</script>

<Select loadOptions={examplePromise} />

Advanced List Positioning / Floating

svelte-select uses floating-ui to control the list floating. See their docs and pass in your config via the floatingConfig prop.

<script>
  import Select from 'svelte-select';

  let floatingConfig = {
    strategy: 'fixed'
  }
</script>

<Select {floatingConfig} />

Exposed methods

These internal functions are exposed to override if needed. Look through the test file (test/src/index.js) for examples.

export let itemFilter = (label, filterText, option) => label.toLowerCase().includes(filterText.toLowerCase());
export let groupBy = undefined;
export let groupFilter = groups => groups;
export let createGroupHeaderItem = groupValue => {
  return {
    value: groupValue,
    label: groupValue
  };
};
export function handleClear() {
  value = undefined;
  listOpen = false;
  dispatch("clear", value);
  handleFocus();
}
export let loadOptions = undefined; // if used must return a Promise that updates 'items'
/* Return an object with { cancelled: true } to keep the loading state as active. */
export const getFilteredItems = () => {
  return filteredItems;
};
export let debounce = (fn, wait = 1) => {
  clearTimeout(timeout);
  timeout = setTimeout(fn, wait);
};

Override core functionality at your own risk! See (get-items.js & filter.js)

    // core replaceable methods...
    <Select 
      filter={...}
      getItems={...}
    />

A11y (Accessibility)

Override these methods to change the aria-context and aria-selection text.

export let ariaValues = (values) => {
  return `Option ${values}, selected.`;
}

export let ariaListOpen = (label, count) => {
  return `You are currently focused on option ${label}. There are ${count} results available.`;
}

export let ariaFocused = () => {
  return `Select is focused, type to refine list, press down to open the menu.`;
}

CSS custom properties (variables)

You can style a component by overriding the available CSS custom properties.

<script>
  import Select from 'svelte-select';
</script>

<Select --border-radius= "10px" --placeholder-color="blue" />

You can also use the inputStyles prop to write in any override styles needed for the input.

<script>
  import Select from 'svelte-select';

  const items = ['One', 'Two', 'Three'];
</script>

<Select {items} inputStyles="box-sizing: border-box;"></Select>

🧪 Experimental: Replace styles (Tailwind, Bootstrap, Bulma etc)

If you'd like to supply your own styles use: import Select from 'svelte-select/no-styles/Select.svelte'. Then somewhere in your code or build pipeline add your own. There is a tailwind stylesheet via import 'svelte-select/tailwind.css'. It uses @extend so PostCSS is required.

License

LIL

NPM DownloadsLast 30 Days