Building a Currency Input Component with shadcn-svelte and Svelte 5
Learn how to create a reusable currency input component using shadcn-svelte and Svelte 5's new runes syntax
Updated
Chris Jayden
On This Page
Creating a user-friendly currency input component can be tricky. In this guide, we'll build a reusable currency input component using shadcn-svelte and Svelte 5's new runes syntax. The component will handle formatting, proper decimal places, and currency symbols automatically.
Features
Automatic currency formatting
Configurable currency and locale
Proper decimal handling
Currency symbol display
Full keyboard support
Compatible with shadcn-svelte's theming
Implementation
Let's create our currency input component. We'll build it on top of shadcn-svelte's base Input component and add currency-specific functionality.
How It Works
Let's break down the key features of our currency input component:
1. Props and Types
The component accepts standard HTML input attributes plus some custom props:
variant: Matches shadcn's input variants
inputSize: Controls input size
currencyFormat: Allows customizing the currency format
2. Currency Formatting
We use the Intl.NumberFormat API for robust currency formatting:
3. Currency Symbol Extraction
The currency symbol is automatically extracted using a derived state:
4. Input Handling
The component handles input events to maintain proper formatting:
Usage
Here's how to use the component in your Svelte application:
Custom Currency Format
You can customize the currency and locale:
Styling
The component inherits shadcn-svelte's theming system, so it will automatically match your application's theme. You can also customize the appearance using the class prop:
Wrapping up
This currency input component provides a robust solution for handling monetary values in your Svelte applications. It combines the power of shadcn-svelte's components with proper currency formatting and user-friendly features. The component is fully typed and takes advantage of Svelte 5's new runes syntax for better reactivity handling.
Feel free to extend this component further based on your needs, such as adding validation, different currency symbols positioning, or additional formatting options.