mui / mui/material-ui

Easy integration of Autocomplete component with react-hook-form

Open
#40,086 4 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs scope: all components
Dominant language
JavaScript
Stars
99.1k
Forks
32.5k
Avg merge
2d 17h
Merged PRs (30d)
106

Description

Duplicates
  • I have searched the existing issues
Latest version
  • I have tested the latest version
Summary 💡

I would like to request a feature where the user can smoothly integrate the Autocomplete component with react-hook-form as any other MUI component.

Examples 🌈
  • Create the nextjs project with npx create-next-app
✔ What is your project named? … my-app
✔ Would you like to use TypeScript? … Yes
✔ Would you like to use ESLint? … No
✔ Would you like to use Tailwind CSS? … No
✔ Would you like to use `src/` directory? … Yes
✔ Would you like to use App Router? (recommended) … No
✔ Would you like to customize the default import alias (@/*)? … No
  • Install mui and react-hook-form
  • Edit the 'src/pages/index.tsx` file
import Head from "next/head";
import { Inter } from "next/font/google";
import styles from "@/styles/Home.module.css";
import {
    Autocomplete,
    Button,
    FormControl,
    FormHelperText,
    InputLabel,
    MenuItem,
    Select,
    TextField,
} from "@mui/material";
import { useForm } from "react-hook-form";

const inter = Inter({ subsets: ["latin"] });

const top5Films = [
    { label: "The Shawshank Redemption", year: 1994 },
    { label: "The Godfather", year: 1972 },
    { label: "The Godfather: Part II", year: 1974 },
    { label: "The Dark Knight", year: 2008 },
    { label: "12 Angry Men", year: 1957 },
];
const ratings = [
    { label: "Ok", value: 0 },
    { label: "Good", value: 1 },
    { label: "Awesome!", value: 2 },
];

export default function Home() {
    const {
        register,
        handleSubmit,
        reset,
        formState: { errors },
    } = useForm({
        defaultValues: {
            film: top5Films[0],
            comment: "I love this",
            rating: 2,
        },
    });
    const onSubmit = (data) => {
        console.log(data);
    };
    return (
        <>
            <Head>
                <title>MUI Feature Request</title>
                <meta
                    name="description"
                    content="Feature request for MUI Autocomplete"
                />
                <meta
                    name="viewport"
                    content="width=device-width, initial-scale=1"
                />
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <main className={`${styles.main} ${inter.className}`}>
                <form onSubmit={handleSubmit(onSubmit)}>
                    <Autocomplete
                        disablePortal
                        options={top5Films}
                        sx={{ width: 300 }}
                        {...register("film")}
                        isOptionEqualToValue={(option, value) =>
                            option.label === value.label
                        }
                        renderInput={(params) => (
                            <TextField {...params} label="Movie" />
                        )}
                    />
                    <FormControl
                        fullWidth
                        error={errors.rating?.message ? true : false}
                    >
                        <InputLabel>Rating</InputLabel>

                        <Select
                            label="Rating"
                            {...register("rating", {
                                required: "This field is required",
                            })}
                            defaultValue={2} // This is also a redundancy, a seperate feature request to eliminate this must be submitted
                        >
                            {ratings?.map((option) => (
                                <MenuItem
                                    key={option.value}
                                    value={option.value}
                                >
                                    {option.label}
                                </MenuItem>
                            ))}
                        </Select>
                        <FormHelperText>
                            {errors.rating?.message?.toString() || ""}
                        </FormHelperText>
                    </FormControl>
                    <TextField label="Comment" {...register("comment")} />
                    <Button type="submit">Submit</Button>
                </form>
            </main>
        </>
    );
}
  • Two things are not behaving as expected
    • Default value: Default value is not automatically selected. It is empty as seen by the user.
    • Final submitted value: The submitted value is always the default value although the user visually sees their selection. The console log is
      image
      no matter what I select.
Motivation 🔦

There are many work arounds while using the Controller component, but nothing works with default values. So currently I am using the MUI Select component in my projects. I hope this feature will help many users.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproduction in src/pages/index.tsx, focusing on Autocomplete's register integration and the reported default-value and submitted-value behavior. Read the Autocomplete and form integration entry points, then determine the supported API and tests needed so selected values and defaults work with react-hook-form without relying on Controller.

Written by the indexing model from the issue text.

Assessment

Tech stack
next.js, react, typescript
Domain
frontend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.