Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active April 18, 2021 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidgilbertson/069038076c0d30e210bbf9fc80884e80 to your computer and use it in GitHub Desktop.
Save davidgilbertson/069038076c0d30e210bbf9fc80884e80 to your computer and use it in GitHub Desktop.
type Nullable<IdType, RequiredType> = RequiredType extends true
? IdType
: IdType | null;
const Select = <IdType extends string, RequiredType extends boolean>(props: {
options: Array<{id: IdType; name: string}>;
selectedItemId: Nullable<IdType, RequiredType>;
onSelect: (id: Nullable<IdType, RequiredType>) => void;
required?: 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