Accessible, customizable Svelte search component.
This search component is composed using semantic form
and input
elements.
See svelte-typeahead for a search component with dropdown results.
Try it in the Svelte REPL.
# npm
npm i svelte-search
# pnpm
pnpm i svelte-search
# Yarn
yarn add svelte-search
# Bun
bun add svelte-search
This component is unstyled by design. Target the component using the [data-svelte-search]
selector.
:global([data-svelte-search] input) {
width: 100%;
font-size: 1rem;
padding: 0.5rem;
margin: 0.5rem 0;
border: 1px solid #e0e0e0;
border-radius: 0.25rem;
}
<script>
import Search from "svelte-search";
let value = "";
</script>
<Search bind:value />
{#if value}
<button on:click={() => (value = "")}>Clear "{value}"</button>
{/if}
The input
element is contained in a form
. Use the forwarded submit
event to obtain the value when pressing "Enter."
<Search bind:value on:submit={() => console.log("submit", value)} />
$$restProps
are forwarded to the input element.
<Search label="My label" placeholder="Placeholder text..." />
<Search>
<span slot="label" style="color: red;">Custom label</span>
</Search>
Set hideLabel
to true
to visually hide the label.
<Search hideLabel label="My label" placeholder="Placeholder text..." />
Use the autofocus
prop to declaratively focus the input.
<Search autofocus />
Bind the ref
prop to programmatically focus the input.
<script>
import Search from "svelte-search";
let ref = null;
</script>
<Search bind:ref />
<button on:click={() => ref.focus()}>Focus</button>
Use the debounce
prop to specify the debounce value in milliseconds.
<script>
import Search from "svelte-search";
let events = [];
</script>
<Search
debounce={800}
on:type={({ detail: value }) => (events = [...events, value])}
/>
<pre>{JSON.stringify(events, null, 2)}</pre>
$$restProps
are forwarded to the input element.
Prop name | Type | Default value |
---|---|---|
value | string |
"" |
label | string |
"Search" |
hideLabel | boolean |
false |
debounce | number |
0 |
ref | HTMLInputElement |
null |
id | string |
"search" + Math.random().toString(36) |
removeFormAriaAttributes | boolean |
false |
autofocus | boolean |
false |
<Search
on:type={(e) => {
console.log("type", e.detail); // input value
}}
on:clear={() => {
console.log("clear");
}}
/>