I’m using React Hook Form to control forms in my React application. I have a component SelectCreateableInputForm which utilizes React Hook Form to manage input.
import { forwardRef, useEffect, useState } from 'react';
import Select, { GroupBase, Props, StylesConfig } from 'react-select';
import CreatableSelect from 'react-select/creatable';
import { useUncontrolled } from '@/hooks/use-uncontolled';
import { cn } from '@/lib/utils';
export const SelectCreateableInput = forwardRef<HTMLSelectElement, Props>(
(props, ref) => {
const { className, value, defaultValue, onChange, ...rest } = props;
const [isMounted, setIsMounted] = useState(false);
// eslint-disable-next-line @typescript-eslint/naming-convention
const [_value, setValue] = useUncontrolled({
value,
defaultValue,
onChange,
});
const handleOnChange = (newValue: unknown) => {
setValue(newValue);
};
useEffect(() => setIsMounted(true), []);
return isMounted ? (
<CreatableSelect
{...rest}
ref={ref as any}
value={_value}
onChange={handleOnChange}
styles={customStyles}
className={cn(className)}
/>
) : null;
}
);
SelectCreateableInput.displayName = 'SelectCreateableInput';
However, when trying to access the value property from the field object passed to the SelectCreateableInput component, the value property isn’t available in that object.
export function SelectCreateableInputForm({
form,
name,
label,
withAsterik = true,
shouldUnregister = true,
description,
className,
error,
selectProps,
}: SelectFormProps) {
return (
<FormField
control={form.control}
name={name}
shouldUnregister={shouldUnregister}
render={({ field }) => (
<FormItem className={className}>
<FormLabel withAsterik={withAsterik}>{label}</FormLabel>
<FormControl>
{/* posisi selectProps harus setelah field agar onChange jalan */}
<SelectCreateableInput
{...field}
{...selectProps}
onChange={selectProps?.onChange || field.onChange}
/>
</FormControl>
{JSON.stringify(field)}
<FormDescription>{description && description}</FormDescription>
<FormMessage>{error && error}</FormMessage>
</FormItem>
)}
/>
);
}
Issue Faced: When attempting to access the value property from the field object passed to the SelectCreateableInput component, the property isn’t available, even though I’ve used form.control and the value property should be there.
<SelectCreateableInputForm
form={form}
label="Variation Name"
name={`variationName[${index}]`}
selectProps={{
isClearable: true,
options: optionsWithDisabled,
isSearchable: true,
onChange: value =>
handleChangeVarName(value as ValueOnchangeProps, index),
}}
/>
I have tried using the Controller from the react hook form directly, but it still doesn’t work.
The form still gets its value, but there will be an issue if this value doesn’t exist. For example, if I change the Select component to another manually via useEffect it won’t change because the value doesn’t work.