- Notifications
You must be signed in to change notification settings - Fork185
Svelte Select. A select component for Svelte
License
rob-balfre/svelte-select
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
💥 Examples of every prop, event, slot and more 💥
npm install svelte-select
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!
Seemigration guide if upgrading
List position and floating is powered byfloating-ui
, see theirpackage-entry-points docs if you encounter build errors.
Prop | Type | Default | Description |
---|---|---|---|
items | any[] | [] | Array of items available to display / filter |
value | any | null | Selected value(s) |
justValue | any | null | READ-ONLY Selected value(s) excluding container object |
itemId | string | value | Override default identifier |
label | string | label | Override default label |
id | string | null | id attr for input field |
filterText | string | '' | Text to filteritems by |
placeholder | string | Please select | Placeholder text |
hideEmptyState | boolean | false | When no items hide list |
listOpen | boolean | false | Open/close list |
class | string | '' | container classes |
containerStyles | string | '' | Add inline styles to container |
clearable | boolean | true | Enable clearing of value(s) |
disabled | boolean | false | Disable select |
multiple | boolean | false | Enable multi-select |
searchable | boolean | true | Iffalse search/filtering is disabled |
groupHeaderSelectable | boolean | false | Enable selectable group headers |
focused | boolean | false | Controls input focus |
listAutoWidth | boolean | true | Iffalse will ignore width of select |
showChevron | boolean | false | Show chevron |
inputAttributes | object | {} | Pass in HTML attributes to Select's input |
placeholderAlwaysShow | boolean | false | Whenmultiple placeholder text will always show |
loading | boolean | false | Showsloading-icon .loadOptions will override this |
listOffset | number | 5 | px space between select and list |
debounceWait | number | 300 | milliseconds debounce wait |
floatingConfig | object | {} | Floating UI Config |
hasError | boolean | false | Iftrue sets error class and styles |
name | string | null | Name attribute of hidden input, helpful for form actions |
required | boolean | false | IfSelect is within a<form> will restrict form submission |
multiFullItemClearable | boolean | false | Whenmultiple selected items will clear on click |
closeListOnChange | boolean | true | Afteron:change list will close |
clearFilterTextOnBlur | boolean | true | Iffalse ,filterText value is preserved on:blur |
<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>
Event Name | Callback | Description |
---|---|---|
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
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}/>
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}/>
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}/>
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={...}/>
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.`;}
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>
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.
About
Svelte Select. A select component for Svelte
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.