Advanced Setup
Advanced setup of tags input with shadecn and tailwind.
Client component
- Create a client component:
"use client";
import { useState } from "react";
import { Tag, TagErrorCode, TagsInput } from "@/components/ui/tags-input";
export default function Example() {
const [selectedTags, setSelectedTags] = useState<Tag[]>([]);
const suggestions: Tag[] = [
{ id: "1", name: "JavaScript" },
{ id: "2", name: "TypeScript" },
{ id: "3", name: "React" },
];
return (
<TagsInput
value={selectedTags}
onChange={setSelectedTags}
suggestions={suggestions}
onlyFromSuggestions={true}
maxTags={3}
placeholder="add tag"
// Customize the component with tailwindcss classes
className=""
inputClassName=""
badgeClassName=""
badgeCloseClassName=""
autocompleteClassName=""
/>
);
}
Add useSWR to fetch suggestions
useSWR is a library for data fetching in React.
Replace the suggestions
array with a function that fetches suggestions from an API.
State suggestions
with useSWR
hook become dynamic and this state becomes data
"use client";
import useSWR from "swr";
import { useState } from "react";
import { Tag, TagErrorCode, TagsInput } from "@/components/ui/tags-input";
const fetcher = (url) => fetch(url).then((res) => res.json());
export default function Example() {
const { data, error, isLoading } = useSWR<Tag[]>(
"https://api.github.com/repos/vercel/swr",
fetcher
);
if (error) return "An error has occurred.";
if (isLoading) return "Loading...";
return (
<TagsInput
suggestions={data}
onlyFromSuggestions={true}
maxTags={3}
placeholder="add tag"
/>
);
}
Only from suggestions
If you want to only allow suggestions, set the onlyFromSuggestions
prop to true
.
<TagsInput onlyFromSuggestions={true} />
If a tag that is not present in the list of suggestions is inserted, the component returns a specific error to handle the display of the error.
Max tags
If you want to limit the number of tags that can be inserted, set the maxTags
prop.
<TagsInput maxTags={3} />
This is props is optionnal and if maxTag is not set, the component will allow an infinite number of tags. Not return an error.
Type Tag[]
The Tag
type is an object with an id
and a name
property.
type Tag = {
id: string;
name: string;
};
New Tag[]
If you want to use a new type for the tags, you can create a new type.
type Tag = {
id: string;
name: string;
};
if tag is in suggestions, the id is defined in the suggestions array and if not in array, for a new tag id is id: new-${Date.now()}
const suggestions: Tag[] = [
{ id: "new-123435667", name: "JavaScript" },
{ id: "2", name: "TypeScript" },
{ id: "3", name: "React" },
];
const searchNewTag = () => {
return suggestions.filter((s) => s.id.startsWith("new-"));
};
// and use timestamp for order by date add in input