1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-11 00:52:29 +01:00

63 lines
2.8 KiB
TypeScript
Raw Normal View History

import React from 'react';
2022-04-04 18:19:59 +02:00
import Select from 'react-select';
import { Controller, Path } from 'react-hook-form';
import { FieldValues } from 'react-hook-form/dist/types/fields';
import { FieldPath } from 'react-hook-form/dist/types/path';
import { FieldPathValue, UnpackNestedValue } from 'react-hook-form/dist/types';
import { FormControlledComponent } from '../../models/form-component';
import { AbstractFormItem, AbstractFormItemProps } from './abstract-form-item';
2022-04-04 18:19:59 +02:00
interface FormSelectProps<TFieldValues, TContext extends object, TOptionValue> extends FormControlledComponent<TFieldValues, TContext>, AbstractFormItemProps<TFieldValues> {
options: Array<selectOption<TOptionValue>>,
valueDefault?: TOptionValue,
2022-04-06 12:24:04 +02:00
onChange?: (value: TOptionValue) => void,
placeholder?: string,
clearable?: boolean,
2022-04-04 18:19:59 +02:00
}
/**
* Option format, expected by react-select
* @see https://github.com/JedWatson/react-select
*/
type selectOption<TOptionValue> = { value: TOptionValue, label: string };
/**
* This component is a wrapper for react-select to use with react-hook-form
*/
export const FormSelect = <TFieldValues extends FieldValues, TContext extends object, TOptionValue>({ id, label, tooltip, className, control, placeholder, options, valueDefault, error, warning, rules, disabled, onChange, readOnly, clearable, formState }: FormSelectProps<TFieldValues, TContext, TOptionValue>) => {
2022-04-06 12:24:04 +02:00
/**
* The following callback will trigger the onChange callback, if it was passed to this component,
* when the selected option changes.
*/
const onChangeCb = (newValue: TOptionValue): void => {
if (typeof onChange === 'function') {
onChange(newValue);
}
};
2022-04-04 18:19:59 +02:00
return (
<AbstractFormItem id={id} label={label} tooltip={tooltip}
2022-04-27 15:36:36 +02:00
className={`form-select ${className || ''}`} formState={formState}
error={error} warning={warning} rules={rules}
disabled={disabled} readOnly={readOnly}>
<Controller name={id as FieldPath<TFieldValues>}
control={control}
defaultValue={valueDefault as UnpackNestedValue<FieldPathValue<TFieldValues, Path<TFieldValues>>>}
render={({ field: { onChange, value, ref } }) =>
<Select ref={ref}
classNamePrefix="rs"
className="rs"
value={options.find(c => c.value === value)}
onChange={val => {
onChangeCb(val.value);
onChange(val.value);
}}
placeholder={placeholder}
isDisabled={readOnly}
isClearable={clearable}
options={options} />
} />
</AbstractFormItem>
2022-04-04 18:19:59 +02:00
);
};