Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

shadcn-multi-select-component

> 前端框架
Open source

A multi-select component designed with shadcn/ui

2.2K stars0 likes0 views
WebsiteGitHub

About

A multi-select component designed with shadcn/ui

MultiSelect Component

A powerful and flexible multi-select component built with React, TypeScript, Tailwind CSS, and shadcn/ui components.

Compatible with: Next.js, Vite, Create React App, and any React environment that supports path aliases and shadcn/ui components.

Features

  • ✨ Multiple Variants: Default, secondary, destructive, and inverted styles
  • Custom Styling: Custom badge colors, icon colors, and gradient backgrounds
  • Grouped Options: Organize options in groups with headings and separators
  • Disabled Options: Mark specific options as disabled and non-selectable
  • Advanced Animations: Multiple animation types (bounce, pulse, wiggle, fade, slide) for badges and popovers
  • Search & Filter: Built-in search functionality with keyboard navigation
  • Dashboard Integration: Perfect for analytics dashboards and data visualization
  • Chart Filtering: Real-time filtering for bar, pie, area, and line charts
  • Multi-level Filtering: Primary and secondary filter combinations
  • Responsive Design: Automatic adaptation to mobile, tablet, and desktop screens
  • Width Constraints: Support for minimum and maximum width settings
  • Mobile-Optimized: Compact mode with touch-friendly interactions
  • Desktop-Enhanced: Full feature set with large displays
  • ♿ Accessibility: Full keyboard support, screen reader compatibility, and ARIA live regions
  • ⌨️ Keyboard Shortcuts: Global hotkeys for navigation and quick actions
  • Imperative Methods: Programmatic control via ref (reset, clear, focus, get/set values)
  • Duplicate Handling: Automatic detection and removal of duplicate options
  • Form Integration: Seamless integration with React Hook Form and validation
  • ️ Customizable Behavior: Auto-close on select, width constraints, empty indicators
  • TypeScript Support: Fully typed with comprehensive TypeScript support
  • Self-Contained: All accessibility features built-in, no external dependencies required

Installation

Prerequisites

This component is compatible with any React project but requires proper setup:

  • React environment: Next.js, Vite, Create React App, or any React setup
  • Path aliases: Configure @/ imports in your bundler
  • shadcn/ui: Install and configure shadcn/ui components
  • Tailwind CSS: Setup and configure Tailwind CSS

1. Copy the Component

bash
cp src/components/multi-select.tsx your-project/components/

2. Install Dependencies

bash
npm install react react-dom
npm install @radix-ui/react-popover @radix-ui/react-separator
npm install lucide-react class-variance-authority clsx tailwind-merge cmdk

3. Setup shadcn/ui Components

Install the required shadcn/ui components:

bash
npx shadcn@latest add button badge popover command separator

4. Configure Path Aliases

For Next.js

Add to your tsconfig.json or jsconfig.json:

json
{
	"compilerOptions": {
		"baseUrl": ".",
		"paths": {
			"@/*": ["./src/*"]
		}
	}
}

For Vite

Add to your vite.config.ts:

typescript
import { defineConfig } from "vite";
import path from "path";

export default defineConfig({
	resolve: {
		alias: {
			"@": path.resolve(__dirname, "./src"),
		},
	},
});

For Webpack/Create React App

You may need to eject or use CRACO to configure path aliases.

5. Setup Utility Function

Ensure you have the cn utility function in src/lib/utils.ts:

typescript
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
	return twMerge(clsx(inputs));
}

Quick Start

Basic Usage

typescript
import { MultiSelect } from "@/components/multi-select";
import { useState } from "react";

const options = [
	{ value: "react", label: "React" },
	{ value: "vue", label: "Vue.js" },
	{ value: "angular", label: "Angular" },
];

function App() {
	const [selectedValues, setSelectedValues] = useState<string[]>([]);

	return (
		<MultiSelect
			options={options}
			onValueChange={setSelectedValues}
			defaultValue={selectedValues}
		/>
	);
}

Custom Styling

typescript
const styledOptions = [
	{
		value: "react",
		label: "React",
		icon: ReactIcon,
		style: {
			badgeColor: "#61DAFB",
			iconColor: "#282C34",
		},
	},
	{
		value: "vue",
		label: "Vue.js",
		icon: VueIcon,
		style: {
			gradient: "linear-gradient(135deg, #4FC08D 0%, #42B883 100%)",
		},
	},
];

<MultiSelect
	options={styledOptions}
	onValueChange={setSelected}
	placeholder="Select with custom styles..."
/>;

Next.js Usage

For Next.js projects, you can use the component in client components with the "use client" directive:

typescript
"use client";

import { MultiSelect } from "@/components/multi-select";
import { useState } from "react";

const options = [
	{ value: "next", label: "Next.js" },
	{ value: "react", label: "React" },
	{ value: "typescript", label: "TypeScript" },
];

export default function MyPage() {
	const [selected, setSelected] = useState<string[]>([]);

	return (
		

	);
}

Grouped Options

typescript
const groupedOptions = [
	{
		heading: "Frontend Frameworks",
		options: [
			{ value: "react", label: "React" },
			{ value: "vue", label: "Vue.js" },
			{ value: "angular", label: "Angular", disabled: true },
		],
	},
	{
		heading: "Backend Technologies",
		options: [
			{ value: "node", label: "Node.js" },
			{ value: "python", label: "Python" },
		],
	},
];

<MultiSelect
	options={groupedOptions}
	onValueChange={setSelected}
	placeholder="Select from groups..."
/>;

Responsive Design

The Multi-Select component includes comprehensive responsive design capabilities that automatically adapt to different screen sizes.

Automatic Responsive Behavior

Enable responsive design with default settings:

typescript
<MultiSelect
	options={options}
	onValueChange={setSelected}
	responsive={true} // Enable automatic responsive behavior
	placeholder="Responsive component"
/>

Default responsive settings:

  • Mobile (< 640px): 2 badges max, compact mode
  • Tablet (640px - 1024px): 4 badges max, normal mode
  • Desktop (> 1024px): 6 badges max, full features

Width Constraints

Control component width with responsive adaptation:

typescript
<MultiSelect
	options={options}
	onValueChange={setSelected}
	responsive={true}
	minWidth="200px"
	maxWidth="400px"
	placeholder="Constrained width"
/>

Dashboard Integration

The Multi-Select component provides powerful integration with analytics dashboards and data visualization libraries.

Basic Dashboard Filtering

typescript
import { MultiSelect } from "@/components/multi-select";
import { BarChart, Bar, XAxis, YAxis, ResponsiveContainer } from "recharts";

const Dashboard = () => {
	const [selectedCategories, setSelectedCategories] = useState(["2024"]);

	const filteredData = data.filter((item) =>
		selectedCategories.includes(item.category)
	);

	return (
		

	);
};

Multi-level Filtering

typescript
const AdvancedDashboard = () => {
	const [primaryFilters, setPrimaryFilters] = useState(["Performance"]);
	const [secondaryFilters, setSecondaryFilters] = useState(["Speed"]);

	return (
		

			<ComposedChart data={filteredData}>
				{/* Multiple chart types combined */}
			</ComposedChart>
		</div>
	);
};

Examples

Basic Multi-Select

typescript
const [selectedValues, setSelectedValues] = useState<string[]>([]);

<MultiSelect
	options={frameworks}
	onValueChange={setSelectedValues}
	defaultValue={selectedValues}
	placeholder="Select frameworks"
/>;

With Icons and Custom Styling

typescript
const [selectedValues, setSelectedValues] = useState<string[]>([]);

<MultiSelect
	options={frameworksWithIcons}
	onValueChange={setSelectedValues}
	defaultValue={selectedValues}
	placeholder="Select technologies"
	variant="inverted"
	maxCount={3}
	modalPopover={true}
/>;

Async Data Loading

typescript
const [options, setOptions] = useState<Option[]>([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
	loadData().then((data) => {
		setOptions(data);
		setLoading(false);
	});
}, []);

<MultiSelect
	options={options}
	onValueChange={setSelectedValues}
	defaultValue={selectedValues}
	placeholder={loading ? "Loading..." : "Select items"}
	disabled={loading}
/>;

API Reference

Best Practices

  1. Always provide meaningful labels: Use descriptive placeholders and aria-labels
  2. Handle loading states: Show loading indicators when fetching async data
  3. Limit display count: Use maxCount for large selections to maintain UI clarity
  4. Use modal on mobile: Set modalPopover={true} for better mobile experience
  5. Implement search: For large option lists, consider adding search functionality
  6. Provide clear feedback: Use the built-in announcements for screen readers

� API Reference

Props

Prop Type Default Description
options MultiSelectOption[] | MultiSelectGroup[] - Array of selectable options or groups
onValueChange (value: string[]) => void - Callback when selection changes
defaultValue string[] [] Initially selected values
placeholder string "Select options" Placeholder text
variant "default" | "secondary" | "destructive" | "inverted" "default" Visual variant
animation number 0 Legacy animation duration in seconds
animationConfig AnimationConfig - Advanced animation configuration
maxCount number 3 Maximum visible selected items
modalPopover boolean false Modal behavior for popover
asChild boolean false Render as child component
className string - Additional CSS classes
hideSelectAll boolean false Hide "Select All" option
searchable boolean true Enable search functionality
emptyIndicator ReactNode - Custom empty state component
autoSize boolean false Allow component to grow/shrink with content
singleLine boolean false Show badges in single line with scroll
popoverClassName string - Custom CSS cla

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptmulti-selectmulti-select-containermulti-select-dropdownmulti-selection

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架