Last active
April 18, 2021 06:45
-
-
Save davidgilbertson/fdf93b467ab198fd5fe86511086ad48f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Nullable<IdType, RequiredType> = RequiredType extends true ? IdType : IdType | null; | |
export type SelectProps<IdType extends string, RequiredType extends boolean> = { | |
options: Array<{id: IdType; name: string}>; | |
selectedItemId: Nullable<IdType, RequiredType>; | |
onSelect: (id: Nullable<IdType, RequiredType>) => void; | |
required?: RequiredType; | |
}; | |
const Select = <IdType extends string, RequiredType extends boolean>( | |
props: SelectProps<IdType, RequiredType>, | |
) => ( | |
<select | |
value={props.selectedItemId ?? 'NULL_SELECTION'} | |
required={props.required} | |
onChange={e => { | |
const selectedId = e.target.value === 'NULL_SELECTION' ? null : e.target.value; | |
props.onSelect(selectedId as Nullable<IdType, RequiredType>); | |
}} | |
> | |
{!props.required && <option value="NULL_SELECTION">None selected</option>} | |
{props.options.map(option => ( | |
<option key={option.id} value={option.id}> | |
{option.name} | |
</option> | |
))} | |
</select> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment