Skip to content

Instantly share code, notes, and snippets.

@alanfoandrade
Last active August 22, 2021 23:29
Show Gist options
  • Save alanfoandrade/d4aa0b1340abf1dbf1be580f05c89e9d to your computer and use it in GitHub Desktop.
Save alanfoandrade/d4aa0b1340abf1dbf1be580f05c89e9d to your computer and use it in GitHub Desktop.
React-select (não async)
import {
FormLabel,
FormControl,
FormErrorMessage,
useTheme,
} from '@chakra-ui/react';
import { Control, Controller, FieldError } from 'react-hook-form';
import Select, {
OptionTypeBase,
Props as SelectProps,
StylesConfig,
} from 'react-select';
interface ISelectProps extends SelectProps<OptionTypeBase> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
control: Control<any>;
name: string;
label?: string;
error?: FieldError;
}
export const ReactSelect = ({
name,
control,
label,
options,
error,
...rest
}: ISelectProps): JSX.Element => {
const theme = useTheme();
const customStyles: StylesConfig<OptionTypeBase, false> = {
menu: (provided) => ({
...provided,
borderRadius: theme.radii.md,
padding: 15,
}),
control: (provided) => ({
...provided,
backgroundColor: theme.colors.gray[100],
borderRadius: theme.radii.md,
height: 48,
padding: '0 4px',
}),
dropdownIndicator: (provided) => ({
...provided,
color: theme.colors.gray[700],
}),
indicatorSeparator: (provided) => ({
...provided,
display: 'none',
}),
option: (provided, state: { isSelected: boolean }) => ({
...provided,
borderRadius: theme.radii.md,
color: state.isSelected ? 'white' : theme.colors.gray[700],
padding: '10px 20px',
marginBottom: 4,
cursor: 'pointer',
}),
};
return (
<FormControl isInvalid={!!error}>
{!!label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<Controller
name={name}
control={control}
{...rest}
render={({ field: { onChange, onBlur, value } }) => (
<Select
value={options.find(c => c.value === value)}
onChange={val => onChange(val.value)}
onBlur={onBlur}
options={options}
getOptionValue={(option) => option.value}
getOptionLabel={(option) => option.label}
styles={customStyles}
placeholder=""
/>
)}
/>
{!!error && (
<FormErrorMessage position="absolute">{error.message}</FormErrorMessage>
)}
</FormControl>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment