Search code examples
javascriptreactjsreact-hook-formzod

Joy Ui Select Element does not change value after choosing an option when I use React Hook Form


This is list of my categories:

export const categories: string[] = [
"Groceries",
"Parts",
"Equipment",
] as const;

This is my Joy Ui Select component inside a Controller component. I am using controller because this select component is controller component. So I need Controller for getting its value when form is submitted.

<Controller
    control={control}
    name={"category"}
    render={({ field: { onChange, onBlur, value, ref } }) => (
        <Select
            ref={ref}
            onChange={onChange}
            value={value ? value : ""}
            onBlur={onBlur}
        >
            {categories.map((category) => (
                <Option
                    label={category}
                    key={category}
                    value={category}
                >
                    {category}
                </Option>
            ))}
        </Select>
    )}
/>

The Problem.

When I select an option from Select component, the value does not appear inside the select box (so that option does not get selected), and when I submit the form I get an error from Zod:

Expected string, received number

Solution

  • I think this way I am overriding the default onChange method of the Select element. That why I changed this line:

    onChange={onChange}
    

    To this line:

    onChange={(e, newValue) => {
        onChange(newValue);
    }}
    

    And it worked.