Middle
Tell me about a custom select component.
sobes.tech AI
Answer from AI
A custom select component is a user interface element that mimics the behavior of the standard HTML <select>, but allows for flexible styling and extended functionality.
Main points:
- Rendering: usually consists of a display field for the selected value and a dropdown list of options.
- State management: stores the current selected value and whether the list is open.
- Event handling: clicks on the field toggle the list, clicks on options change the selected value.
- Accessibility: it is important to support keyboard navigation (arrow keys, Enter for selection) and ARIA attributes for screen readers.
Example of a simple custom select in React:
function CustomSelect({ options, value, onChange }) {
const [open, setOpen] = React.useState(false);
return (
<div tabIndex={0} onBlur={() => setOpen(false)}>
<div onClick={() => setOpen(!open)}>{value || 'Select'}</div>
{open && (
<ul>
{options.map(opt => (
<li key={opt.value} onClick={() => { onChange(opt.value); setOpen(false); }}>
{opt.label}
</li>
))}
</ul>
)}
</div>
);
}
Such a component can be extended by adding support for search, multi-select, asynchronous loading of options, etc.