-
Notifications
You must be signed in to change notification settings - Fork 3
DropDown
Kea-Roy Ong edited this page Nov 24, 2024
·
2 revisions
The DropDown component is a reusable dropdown menu that displays a button and a list of selectable items. It leverages Material-UI components for consistent styling and behavior.
To use the DropDown component, import it and provide an array of menu items, each containing an item name and a callback function.
Props:
-
[menuItems]
: An array of objects, each with:-
[item]
: A string representing the menu item name. -
[callback]
: A function to be called when the item is selected.
-
-
[isMobile]
(optional): A boolean indicating if the dropdown is displayed on a mobile device. This is used to inform the component if it should be rendered in a mobile or desktop state. -
[defaultValue]
(optional): A string representing the default selected item. It must be a value in menuItems. If it is not provided, the first menuItem is the default. -
[className]
(optional): A string for custom CSS class. This is normally used to add your own custom styling to the component. -
[icon]
(optional): If true, a dropdown arrow will be displayed. If false, no icon is shown.
const menuItems = [
{ item: 'Price', callback: () => setSortBy('avgPrice') },
{ item: 'Rating', callback: () => setSortBy('avgRating') },
{ item: 'Date Added', callback: () => setSortBy('id') },
];
function App() {
return <DropDown menuItems={menuItems} defaultValue={'Rating'} icon={true}/>;
}
- The component renders a button with the default or first menu item displayed.
- Clicking the button opens a dropdown menu with the provided items.
- Selecting an item triggers its callback function and updates the button text to the selected item.
- Empty menuItems array: The component handles this by displaying an empty menu.
- Duplicate item names: Callbacks are correctly associated with their respective items even if there are multiple items with the same name.
- Long item names: This is not handled by the component and relies on the client's personal styling through the
className
prop
- State Management: Use useState to manage the selected item and the dropdown's open state.
- Event Handling: Implement handlers for button clicks and menu item selection.
- Styling: Use Material-UI's Button, Menu, and MenuItem components for consistent styling.
- Accessibility: Ensure the component is accessible by setting appropriate ARIA attributes.
- Initialization: O(1) for setting initial state.
- Rendering: O(n) where n is the number of menu items, as each item is rendered in the dropdown.
- Event Handling: O(1) for handling clicks and state updates.