Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/sersavan/shadcn-multi-select-component

A multi-select component designed with shadcn/ui
https://github.com/sersavan/shadcn-multi-select-component

nextjs reactjs shadcn-ui

Last synced: 23 days ago
JSON representation

A multi-select component designed with shadcn/ui

Awesome Lists containing this project

README

        

## Multi-Select Component Setup in Next.js

### Prerequisites

Ensure you have a Next.js project set up. If not, create one:

```bash
npx create-next-app my-app --typescript
cd my-app
```

### Step 1: Install shadcn Components

Install required shadcn components:

```bash
npx shadcn@latest init
npx shadcn@latest add command popover button separator badge
```

### Step 2: Create the Multi-Select Component

Create `multi-select.tsx` in your `components` directory:

```tsx
// src/components/multi-select.tsx

import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import {
CheckIcon,
XCircle,
ChevronDown,
XIcon,
WandSparkles,
} from "lucide-react";

import { cn } from "@/lib/utils";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@/components/ui/command";

/**
* Variants for the multi-select component to handle different styles.
* Uses class-variance-authority (cva) to define different styles based on "variant" prop.
*/
const multiSelectVariants = cva(
"m-1 transition ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-300",
{
variants: {
variant: {
default:
"border-foreground/10 text-foreground bg-card hover:bg-card/80",
secondary:
"border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
inverted: "inverted",
},
},
defaultVariants: {
variant: "default",
},
}
);

/**
* Props for MultiSelect component
*/
interface MultiSelectProps
extends React.ButtonHTMLAttributes,
VariantProps {
/**
* An array of option objects to be displayed in the multi-select component.
* Each option object has a label, value, and an optional icon.
*/
options: {
/** The text to display for the option. */
label: string;
/** The unique value associated with the option. */
value: string;
/** Optional icon component to display alongside the option. */
icon?: React.ComponentType<{ className?: string }>;
}[];

/**
* Callback function triggered when the selected values change.
* Receives an array of the new selected values.
*/
onValueChange: (value: string[]) => void;

/** The default selected values when the component mounts. */
defaultValue?: string[];

/**
* Placeholder text to be displayed when no values are selected.
* Optional, defaults to "Select options".
*/
placeholder?: string;

/**
* Animation duration in seconds for the visual effects (e.g., bouncing badges).
* Optional, defaults to 0 (no animation).
*/
animation?: number;

/**
* Maximum number of items to display. Extra selected items will be summarized.
* Optional, defaults to 3.
*/
maxCount?: number;

/**
* The modality of the popover. When set to true, interaction with outside elements
* will be disabled and only popover content will be visible to screen readers.
* Optional, defaults to false.
*/
modalPopover?: boolean;

/**
* If true, renders the multi-select component as a child of another component.
* Optional, defaults to false.
*/
asChild?: boolean;

/**
* Additional class names to apply custom styles to the multi-select component.
* Optional, can be used to add custom styles.
*/
className?: string;
}

export const MultiSelect = React.forwardRef<
HTMLButtonElement,
MultiSelectProps
>(
(
{
options,
onValueChange,
variant,
defaultValue = [],
placeholder = "Select options",
animation = 0,
maxCount = 3,
modalPopover = false,
asChild = false,
className,
...props
},
ref
) => {
const [selectedValues, setSelectedValues] =
React.useState(defaultValue);
const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
const [isAnimating, setIsAnimating] = React.useState(false);

const handleInputKeyDown = (
event: React.KeyboardEvent
) => {
if (event.key === "Enter") {
setIsPopoverOpen(true);
} else if (event.key === "Backspace" && !event.currentTarget.value) {
const newSelectedValues = [...selectedValues];
newSelectedValues.pop();
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
}
};

const toggleOption = (option: string) => {
const newSelectedValues = selectedValues.includes(option)
? selectedValues.filter((value) => value !== option)
: [...selectedValues, option];
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
};

const handleClear = () => {
setSelectedValues([]);
onValueChange([]);
};

const handleTogglePopover = () => {
setIsPopoverOpen((prev) => !prev);
};

const clearExtraOptions = () => {
const newSelectedValues = selectedValues.slice(0, maxCount);
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
};

const toggleAll = () => {
if (selectedValues.length === options.length) {
handleClear();
} else {
const allValues = options.map((option) => option.value);
setSelectedValues(allValues);
onValueChange(allValues);
}
};

return (



{selectedValues.length > 0 ? (



{selectedValues.slice(0, maxCount).map((value) => {
const option = options.find((o) => o.value === value);
const IconComponent = option?.icon;
return (

{IconComponent && (

)}
{option?.label}
{
event.stopPropagation();
toggleOption(value);
}}
/>

);
})}
{selectedValues.length > maxCount && (

{`+ ${selectedValues.length - maxCount} more`}
{
event.stopPropagation();
clearExtraOptions();
}}
/>

)}


{
event.stopPropagation();
handleClear();
}}
/>




) : (


{placeholder}



)}


setIsPopoverOpen(false)}
>



No results found.





(Select All)

{options.map((option) => {
const isSelected = selectedValues.includes(option.value);
return (
toggleOption(option.value)}
className="cursor-pointer"
>



{option.icon && (

)}
{option.label}

);
})}




{selectedValues.length > 0 && (
<>

Clear


>
)}
setIsPopoverOpen(false)}
className="flex-1 justify-center cursor-pointer max-w-full"
>
Close






{animation > 0 && selectedValues.length > 0 && (
setIsAnimating(!isAnimating)}
/>
)}

);
}
);

MultiSelect.displayName = "MultiSelect";
```

### Step 3: Integrate the Component

Update `page.tsx`:

```tsx
// src/app/page.tsx

"use client";

import React, { useState } from "react";
import { MultiSelect } from "@/components/multi-select";
import { Cat, Dog, Fish, Rabbit, Turtle } from "lucide-react";

const frameworksList = [
{ value: "react", label: "React", icon: Turtle },
{ value: "angular", label: "Angular", icon: Cat },
{ value: "vue", label: "Vue", icon: Dog },
{ value: "svelte", label: "Svelte", icon: Rabbit },
{ value: "ember", label: "Ember", icon: Fish },
];

function Home() {
const [selectedFrameworks, setSelectedFrameworks] = useState(["react", "angular"]);

return (


Multi-Select Component




Selected Frameworks:



    {selectedFrameworks.map((framework) => (
  • {framework}

  • ))}



);
}

export default Home;
```

### Step 4: Run Your Project

```bash
npm run dev
```