defaultValue
The defaultValue
prop allows you to initialize Chipster with a predefined set of items. This is useful for editing existing data or providing initial values.
Type Definition
type DefaultValue = string[];
Basic Usage
BasicExample.tsx
import { Chipster } from '@micoblanc/chipster'
export default function BasicExample() {
const initialTags = ['React', 'TypeScript', 'Tailwind']
return (
<Chipster defaultValue={initialTags}>
<Chipster.ItemList />
<Chipster.Input placeholder="Add more tags..." />
</Chipster>
)
}
Advanced Usage with External Data
ExternalDataExample.tsx
export default function ExternalDataExample() {
const [initialData, setInitialData] = useState<string[]>([])
useEffect(() => {
const fetchData = async () => {
const data = await fetchUserTags()
setInitialData(data)
}
fetchData()
}, [])
return (
<Chipster
defaultValue={initialData}
onAdd={(value) => updateUserTags([...initialData, value])}
>
<Chipster.ItemList />
<Chipster.Input placeholder="Add tags..." />
<Chipster.Validation
maxItems={10}
allowDuplicates={false}
/>
</Chipster>
)
}
With Validation and Transformation
ValidationExample.tsx
export default function ValidationExample() {
const initialEmails = ['[email protected]', '[email protected]']
return (
<Chipster defaultValue={initialEmails}>
<Chipster.ItemList />
<Chipster.Input placeholder="Add email..." />
<Chipster.Validation
validationRules={[
{
test: (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
message: 'Invalid email format'
}
]}
transform={(v) => v.toLowerCase().trim()}
maxItems={5}
allowDuplicates={false}
/>
</Chipster>
)
}
Important Notes
- Initial values are validated against validation rules if provided
- Duplicates are handled based on
allowDuplicates
setting - Maximum items limit is respected
- Each item gets a unique ID automatically
- Initial values can be transformed using the
transform
function - Empty strings are filtered out automatically
- Initial values are immutable (component maintains its own state)
Common Use Cases
- Form editing
- Data persistence
- Pre-populated lists
- Default configurations
- User preferences
- Saved searches
- Category management
- Tag restoration
With Suggestions
SuggestionsWithDefaultExample.tsx
export default function SuggestionsWithDefaultExample() {
const defaultTechnologies = ['React', 'TypeScript']
const allTechnologies = ['React', 'TypeScript', 'JavaScript', 'Next.js']
const getSuggestions = useCallback((input: string) => {
return allTechnologies
.filter(tech =>
tech.toLowerCase().includes(input.toLowerCase()) &&
!defaultTechnologies.includes(tech)
)
.map(tech => ({ label: tech }))
}, [])
return (
<Chipster defaultValue={defaultTechnologies}>
<Chipster.ItemList />
<Chipster.Input placeholder="Add technology..." />
<Chipster.Suggestions getSuggestions={getSuggestions} />
</Chipster>
)
}