Search code examples
htmlreactjsnext.jsreact-hook-formchakra-ui

Setting Default Value in Select Menus With react-hook-form


I'm trying to set the default value of a select menu from chakra-react-select in a form but i am unsuccessful in acheiving this.

This is the code:

<form onSubmit={handleSubmit(onSubmit)}>
                    <Flex justifyContent="space-between" mt={8}>
                        <Flex flexDir={"column"} justifyContent={"space-between"} align={"flex-start"}>
                            <Heading size={"sm"}>Prefix</Heading>
                            <Text color={"gray.300"}>Configure the prefix for the guild.</Text>
                            <Input
                                paddingTop={"1px"}
                                placeholder="Enter prefix here"
                                size='md'
                                {...register("prefix", { maxLength: { value: 5, message: "Max length exceeded" }, minLength: { value: 1, message: "Minimum length is 1" }, required: { value: true, message: "This field is required." } })}
                            />
                        </Flex>
                        <Flex flexDir={"column"} justifyContent={"space-between"} align={"flex-end"}>
                            <Heading size={"sm"}>Language</Heading>
                            <Text color={"gray.300"}>Configure the language for the guild.</Text>
                            <Controller
                                name="language"
                                control={control}
                                defaultValue="🇺🇸 English"
                                rules={selectMenuRules.language}
                                render={({ field }) => (
                                    <Select className='select-menu' options={availableLanguages} {...field} />
                                )}
                            />
                        </Flex>
                    </Flex>
                    <br />
                </form>

Solution

  • Using a string 🇺🇸 English as defaultValue seems to be the issue. You can try using something like availableLanguages[0].value for defaultValue prop.

    Edit:

    You can try using just availableLanguages[0]. Also React Hook Form advanced usage section have some examples for react-select with Controller component. These might help.

    https://react-hook-form.com/advanced-usage