Last active
January 16, 2020 01:46
-
-
Save aaronhayes/a38d87f846b9a3041c391b3842e65b1a to your computer and use it in GitHub Desktop.
mui-rff-autocomplete
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
import React, { ChangeEvent } from 'react'; | |
import { Field, FieldRenderProps, FieldProps } from 'react-final-form'; | |
import TextField, { TextFieldProps as MuiTextFieldProps } from '@material-ui/core/TextField'; | |
import { | |
default as MuiAutocomplete, | |
AutocompleteProps as MuiAutocompleteProps | |
} from '@material-ui/lab/Autocomplete'; | |
type AutocompleteOption = { | |
[key: string]: any; | |
}; | |
interface AutocompleteProps extends Partial<MuiAutocompleteProps> { | |
name: string; | |
label: string; | |
getOptionValue: (option: any) => any; | |
options: AutocompleteOption[]; | |
required?: boolean; | |
fieldProps?: FieldProps<any, any>; | |
textFieldProps?: Partial<MuiTextFieldProps>; | |
} | |
const Autocomplete = (props: AutocompleteProps) => { | |
const { name, fieldProps, ...rest } = props; | |
return ( | |
<Field | |
name={name} | |
render={fieldRenderProps => <AutocompleteWrapper {...fieldRenderProps} {...rest} />} | |
{...fieldProps} | |
/> | |
); | |
}; | |
interface MuiRffAutocompleteProps extends FieldRenderProps<MuiTextFieldProps, HTMLElement> { | |
label: string; | |
textFieldProps?: Partial<MuiTextFieldProps>; | |
getOptionValue: (option: any) => any; | |
} | |
const AutocompleteWrapper = (props: MuiRffAutocompleteProps) => { | |
const { | |
input: { name, onChange, value, multiple, ...restInput }, | |
meta, | |
label, | |
textFieldProps, | |
getOptionValue, | |
...rest | |
} = props; | |
const showError = | |
((meta.submitError && !meta.dirtySinceLastSubmit) || meta.error) && meta.touched; | |
return ( | |
<MuiAutocomplete | |
{...rest} | |
multiple={multiple} | |
onChange={ | |
multiple | |
? (_e: ChangeEvent<{}>, values: any[]): void => { | |
onChange(values.map(getOptionValue)); | |
} | |
: (_e: ChangeEvent<{}>, option: any): void => { | |
option ? onChange(getOptionValue(option)) : onChange(undefined); | |
} | |
} | |
renderInput={params => ( | |
<TextField | |
label={label} | |
{...params} | |
{...restInput} | |
{...textFieldProps} | |
fullWidth | |
variant="standard" | |
margin="normal" | |
error={showError} | |
helperText={showError ? meta.error || meta.submitError : undefined} | |
/> | |
)} | |
/> | |
); | |
}; | |
export default Autocomplete; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment