Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Svelte Select. A select component for Svelte

License

NotificationsYou must be signed in to change notification settings

rob-balfre/svelte-select

Repository files navigation

Svelte Select

Svelte Select

versiondownloads
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

Svelte 5

I'm not currently using Svelte 5 in my day job or personal projects so might be a while before I tackle porting / upgrading to Svelte 5. Looking forward to it though, just need to find the time!

Upgrading Svelte Select

Seemigration guide if upgrading

Rollup and low/no-build setups

List position and floating is powered byfloating-ui, see theirpackage-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 filteritems 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
searchablebooleantrueIffalse search/filtering is disabled
groupHeaderSelectablebooleanfalseEnable selectable group headers
focusedbooleanfalseControls input focus
listAutoWidthbooleantrueIffalse will ignore width of select
showChevronbooleanfalseShow chevron
inputAttributesobject{}Pass in HTML attributes to Select's input
placeholderAlwaysShowbooleanfalseWhenmultiple placeholder text will always show
loadingbooleanfalseShowsloading-icon.loadOptions will override this
listOffsetnumber5px space between select and list
debounceWaitnumber300milliseconds debounce wait
floatingConfigobject{}Floating UI Config
hasErrorbooleanfalseIftrue sets error class and styles
namestringnullName attribute of hidden input, helpful for form actions
requiredbooleanfalseIfSelect is within a<form> will restrict form submission
multiFullItemClearablebooleanfalseWhenmultiple selected items will clear on click
closeListOnChangebooleantrueAfteron:change list will close
clearFilterTextOnBlurbooleantrueIffalse,filterText value is preserved on:blur

Named slots

<Select>  <divslot="prepend" />  <divslot="selection"let:selectionlet:index /><!-- index only available when multiple -->  <divslot="clear-icon" />    <divslot="multi-clear-icon" />    <divslot="loading-icon" />    <divslot="chevron-icon" />   <divslot="list-prepend" />    <divslot="list"let:filteredItems />    <divslot="list-append" />    <divslot="item"let:itemlet:index />    <divslot="input-hidden"let:value />  <divslot="required"let:value /><!-- Remember you can also use `svelte:fragment` to avoid a container DOM element. -->  <svelte:fragmentslot="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 whenloadOptions resolves
error{ type, details }fires when error is caught
filter{ detail }fires whenlistOpen: true and items are filtered
hoverItem{ detail }fires when hoverItemIndex changes

Items

items can be simple arrays or collections.

<script>importSelectfrom'svelte-select';letsimple=['one','two','three'];letcollection=[{value:1,label:'one'},{value:2,label:'two'},{value:3,label:'three'},];</script><Selectitems={simple}/><Selectitems={collection}/>

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

<script>importSelectfrom'svelte-select';constitems=[{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'}];constgroupBy=(item)=>item.group;</script><Select{items}{groupBy}/>

You can also use custom collections.

<script>importSelectfrom'svelte-select';constitemId='id';constlabel='title';constitems=[{id:0,title:'Foo'},{id:1,title:'Bar'},];</script><Select{itemId}{label}{items}/>

Async Items

To load items asynchronously thenloadOptions is the simplest solution. Supply a function that returns aPromise that resolves with a list of items.loadOptions has debounce baked in and fires each timefilterText is updated.

<script>importSelectfrom'svelte-select';import{someApiCall}from'./services';asyncfunctionexamplePromise(filterText){// Put your async code here...// For example call an API using filterText as your search params// When your API responds resolve your Promiseletres=awaitsomeApiCall(filterText);returnres;}</script><SelectloadOptions={examplePromise}/>

Advanced List Positioning / Floating

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

<script>importSelectfrom'svelte-select';letfloatingConfig={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.

exportletitemFilter=(label,filterText,option)=>label.toLowerCase().includes(filterText.toLowerCase());
exportletgroupBy=undefined;
exportletgroupFilter=groups=>groups;
exportletcreateGroupHeaderItem=groupValue=>{return{value:groupValue,label:groupValue};};
exportfunctionhandleClear(){value=undefined;listOpen=false;dispatch("clear",value);handleFocus();}
exportletloadOptions=undefined;// if used must return a Promise that updates 'items'/* Return an object with { cancelled: true } to keep the loading state as active. */
exportconstgetFilteredItems=()=>{returnfilteredItems;};
exportletdebounce=(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...<Selectfilter={...}getItems={...}/>

A11y (Accessibility)

Override these methods to change thearia-context andaria-selection text.

exportletariaValues=(values)=>{return`Option${values}, selected.`;}exportletariaListOpen=(label,count)=>{return`You are currently focused on option${label}. There are${count} results available.`;}exportletariaFocused=()=>{return`Select is focused, type to refine list, press down to open the menu.`;}

CSS custom properties (variables)

You can style a component by overridingthe available CSS custom properties.

<script>importSelectfrom'svelte-select';</script><Select--border-radius= "10px"--placeholder-color="blue"/>

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

<script>importSelectfrom'svelte-select';constitems=['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 viaimport 'svelte-select/tailwind.css'. It uses@extend so PostCSS is required.

License

LIL

About

Svelte Select. A select component for Svelte

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors47


[8]ページ先頭

©2009-2025 Movatter.jp