I wanted to show the title on the drop down menu and when some one select an option and submit i wanted the year value should be submitted

Viewed 73

I wanted to show the title on the material-ui Autocomplete drop down menu and when someone selects an option and submits I want the the year value to be submitted (register to RHF):

import React from "react";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";

function App() {
  const { control, handleSubmit, register } = useForm();
  const onSubmit = (data) => console.log(data);
  const top100Films = [
    { title: "The Shawshank Redemption", value: 1994 },
    { title: "The Godfather", year: 1972 },
    { title: "The Godfather: Part II", year: 1974 }
  ];
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Autocomplete
        id="combo-box-demo"
        options={top100Films}
        getOptionLabel={(option) => option.title}
   
        style={{ width: 300 }}
        renderInput={(params) => (
          <TextField
            {...params}
            inputRef={register}
            name="formfield"
            label="Combo box"
            variant="outlined"
          />
        )}
      />

      <input type="submit" />
    </form>
  );
}

export default App;
1 Answers

Ciao, finally I found a solution for this problem. This is the code:

import React from "react";
import "./styles.css";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "@material-ui/core";
import { Autocomplete } from "@material-ui/lab";

const top100Films = [
  { _id: 1, title: "The Shawshank Redemption", year: 1994 },
  { _id: 2, title: "The Godfather", year: 1972 },
  { _id: 3, title: "The Godfather: Part II", year: 1974 }
];

export default function App() {
  const { register, handleSubmit, control } = useForm();

  const getOpObj = (option) => {
    if (!option) return option;
    if (!option._id) option = top100Films.find((op) => op._id === option);
    return option;
  };

  const onSubmit = (data) => {
    console.log(top100Films[data.film - 1].year);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="film"
        as={
          <Autocomplete
            options={top100Films}
            getOptionLabel={(option) => getOpObj(option).title}
            style={{ width: 300 }}
            getOptionSelected={(option, value) => {
              if (!option) return option;
              return option._id === getOpObj(value)._id;
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                name="formfield"
                label="Combo box"
                variant="outlined"
              />
            )}
          />
        }
        onChange={([, obj]) => {
          const op = getOpObj(obj);
          if (op) return getOpObj(obj)._id;
          return null;
        }}
        control={control}
        defaultValue={null}
      />
      <input type="submit" />
    </form>
  );
}  

Explanation:

As you can see top100Films now contains an additional attribute _id. I needed it because I found a strange behaviour on functions for getOptionLabel, getOptionSelected and onChange. These functions sometimes receive the the option structure (and this is what we expect) and sometimes receive a value (and this value will be acceptable only if options contains an attribute called _id that starts from 1).

I don't know why this happens. Maybe is the Controller component in combination with Autocomplete. Maybe Autocomplete contains some errors. Maybe Controller accepts options only in a particular way. I really don't know.

So now on submit, the data you receive (if you select for example "The Shawshank Redemption") are:

{
   film: 1
}

And finally, to get the year of the selected element you could do

top100Films[data.film - 1].year

Here the codesandbox example.

Related