How to use the Select component from Bits UI with Formsnap.
The Select component from Bits UI is a simple, yet powerful component for building a custom select menu. It powers the Select component for shadcn-svelte, which is one of the most popular UI projects for Svelte. This recipe will demonstrate how to integrate that component with Formsnap.
Single Select
We're going to build a "languages" select menu that allows the user to select a single language from a list of pre-defined options. We'll use a code to represent the language's value, and the language's name as the label.
Define the Schema
Here's the schema we'll use for the form we'll build in this guide. We'll assume you know how to setup the load function and actions in the +page.server.ts file.
Setup the Form
We apply the attrs to the Select.Trigger component so that the label and other accessibility attributes are associated with it instead of the hidden Select.Input.
This enables the user to click the label to open the select menu, and also allows validation errors to automatically associate with the trigger element, which is the control in this case.
Warning
Only apply the name attribute to the Select.Input. Do not spread the entire attrs object onto it or you will have duplicate id attributes which creates invalid HTML and a mess of accessibility issues.
Finished Product
That's it! 🎉
With some additional styles and structure, the form could look something like this:
Multiple Select
The <Select /> component also supports multiple selection. Here's how you can use it to build a multi-select form.
Define the Schema
Here's the schema we'll use for the form we'll build in this guide. We'll assume you know how to setup the load function and actions in the +page.server.ts file.
Setup the Form
Notice that we need to use a hidden input for each selected value in the multiple select. This enables SuperForms to properly track the values and validate them on the server.
Warning
Only apply the name attribute to the Select.Input. Do not spread the entire attrs object onto it or you will have duplicate id attributes which creates invalid HTML and a mess of accessibility issues.
Finished Product
That's it! 🎉
With some additional styles and structure, the form could look something like this: