Published on

How to use dynamic list for Shadcn ui select component

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Use a Dynamic List for the Shadcn UI Select Component

Dynamic lists in UI components are essential for building scalable and reusable React applications. This guide walks you through implementing a dynamic list in the Shadcn UI Select component, avoiding hardcoding while ensuring seamless functionality.

Prerequisites

Before proceeding, ensure you have:

  1. A React project set up.
  2. The Shadcn UI library installed.
  3. Familiarity with JavaScript array methods like map().

Step-by-Step Implementation

Step 1: Install the Required Library

Ensure the Shadcn UI library is installed in your project. If not, install it using npm or yarn:

npm install @shadcn/ui

Step 2: Prepare Your Dynamic List

Create a list of items you want to render in your Select component. For example:

const items = [
  { id: 1, label: 'Option 1' },
  { id: 2, label: 'Option 2' },
  { id: 3, label: 'Option 3' },
]

Step 3: Implement the Shadcn UI Select Component

Use the map() function to dynamically generate SelectItem components from your list:

import React from 'react'
import { Select, SelectTrigger, SelectContent, SelectItem } from '@shadcn/ui'

const DynamicSelect = () => {
  const items = [
    { id: 1, label: 'Option 1' },
    { id: 2, label: 'Option 2' },
    { id: 3, label: 'Option 3' },
  ]

  return (
    <Select>
      <SelectTrigger aria-label="Select an option">Select an option</SelectTrigger>
      <SelectContent>
        {items.map((item) => (
          <SelectItem key={item.id} value={item.label}>
            {item.label}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  )
}

export default DynamicSelect

Explanation

  1. Dynamic Rendering: The map() function loops through the items array and creates a SelectItem for each object.
  2. Unique Keys: Each SelectItem uses a unique key (item.id), which is essential for React to optimize rendering.
  3. Dynamic Value: The value and displayed label are derived from the items array, making the list dynamic.

Common Issues and Solutions

1. Items Not Showing

  • Issue: If items are not appearing, ensure that the items array is correctly defined and contains data.
  • Solution: Add a console.log(items) to debug if data is correctly passed.

2. Missing or Incorrect Keys

  • Issue: React throws a warning about missing keys.
  • Solution: Ensure each item in the list has a unique id or key.

3. Styling Issues

  • Issue: The dropdown might not look as expected.
  • Solution: Ensure you’ve included the necessary styles for the Shadcn UI components.

Additional Tips

  1. Data from APIs: You can fetch items dynamically from an API and use the same approach to render them.
useEffect(() => {
  fetch('https://api.example.com/items')
    .then((response) => response.json())
    .then((data) => setItems(data))
}, [])
  1. Default Selection: Use the value prop on the Select component to set a default value.

  2. Accessibility: Always provide aria-label or similar attributes for better accessibility.

Conclusion

By following this guide, you’ve successfully implemented a dynamic list in the Shadcn UI Select component. This approach ensures your application remains scalable and maintainable.


FAQs

How can I add a default value?

Use the value prop on the Select component to specify a default value:

<Select value="Option 1">...</Select>

Can I style the Select component?

Yes, Shadcn UI supports customization through CSS or utility classes. Refer to the Shadcn UI documentation for styling details.

What if my items come from an API?

Fetch the data in a useEffect hook and store it in state:

useEffect(() => {
  fetch('API_ENDPOINT')
    .then((res) => res.json())
    .then((data) => setItems(data))
}, [])

Why is my dropdown not showing items?

Check if the items array is populated and correctly mapped. Also, verify that the necessary styles and dependencies are properly included.