MUI: Autocomplete received an invalid value. None of the options correspond to the value of `0`

Currently, I am utilizing the MUI autocomplete feature in conjunction with react-hook-form. I have meticulously followed the guidance provided in this insightful response.

ControlledAutoComplete.jsx

import { Autocomplete, TextField } from "@mui/material";
import React from "react";
import { Controller } from "react-hook-form";

const ControlledAutoComplete = ({
  options = [],
  label,
  renderInput,
  getOptionLabel,
  control,
  defaultValue,
  name,
  errors,
}) => {
  return (
    <Controller
      defaultValue={defaultValue}
      name={name}
      control={control}
      render={({ field }) => (
        <Autocomplete
          options={options}
          getOptionLabel={getOptionLabel}
          defaultValue={defaultValue}
          renderInput={(params) => (
            <TextField
              {...params}
              label={label}
              error={errors[name]}
              helperText={errors[name] && errors[name].message}
              onChange={(e, data) => field.onChange(data)}
            />
          )}
          {...field}
          isOptionEqualToValue={(option, value) =>
            value === undefined || value === "" || option.id === value.id
          }
        />
      )}
    />
  );
};

export default ControlledAutoComplete;

AddFees.jsx

          <ControlledAutoComplete
            control={control}
            name="enrollmentId"
            options={[{ id: 1, firstName: "John"}, { id: 2, firstName: "Jen" }]}
            getOptionLabel={(option) => `${option.firstName}`}
            label="Select Students"
            errors={errors}
            defaultValue={""}
          />

I have encountered a warning message that states,

MUI: The inputted value for the Autocomplete component is deemed invalid. None of the selections align with 0. You can utilize the isOptionEqualToValue property to customize the comparison method.

Answer №1

My approach was incorrect. Instead of listening for onChange on the text field, it should have been on the AutoComplete component.

const ControlledAutoComplete = ({
  options = [],
  label,
  renderInput,
  getOptionLabel,
  control,
  defaultValue,
  name,
  errors,
}) => {
  return (
    <Controller
      name={name}
      control={control}
      defaultValue={defaultValue}
      render={({ field }) => (
        <Autocomplete
          options={options}
          getOptionLabel={getOptionLabel}
          renderInput={(params) => (
            <TextField
              {...params}
              label={label}
              error={errors[name]}
              helperText={errors[name] && errors[name].message}
            />
          )}
          {...field}
          isOptionEqualToValue={(option, value) =>
            value === undefined || value === "" || option.id === value.id
          }
          onChange={(_, data) => field.onChange(data)}
        />
      )}
    />
  );
};

Here's how you can use it:

          <ControlledAutoComplete
            control={control}
            name="enrollmentId"
            options={students}
            getOptionLabel={(option) => `${option.firstName}`}
            label="Select Students"
            errors={errors}
            defaultValue=""
          />

Check out this sandbox example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some tips for creating an improved React list container component?

I have a small application that fetches movie data. The component hierarchy is not very complex. The state is stored in App.js and then passed down to the Movies.js component, which simply displays a list of movies in a ul element. Data passing from App.j ...

I noticed that when using Next.js with the `revalidate: 1` option on a static page, it is triggering two full F5 refresh actions instead of just one. I was hoping for

Currently, I have set up a blog post edit page in my Next.js project. The post pages are utilizing the Incremental Static Regeneration feature with a revalidation time of 1 second for testing purposes. In the future, I plan to increase this to a revalidat ...

Is it feasible to capture a screenshot of a URL by using html2canvas?

Is it possible to take a screenshot of a specific URL using html2canvas? For example, if I have the following URLs: mydomain.com/home mydomain.com/home?id=2 mydomain.com/home/2 How can I capture and display the screenshot image on another page? window ...

What is the process for transferring a function to reducers in Redux Toolkit?

In one of my files called Main.tsx, I have a function that sends a request and retrieves data: async function fetchProducts(productsPage = 1, id?: number) { const itemsPerPage = 5 let url: string if (id) { url = `https://reqres.in/api/ ...

Currently experimenting with jQuery in conjunction with the reddit API to generate individual divs for every post

Issue with displaying post titles, URLs, and permalinks separately. Need them to display together for each post. See the code below: $(document).ready(function() { $.getJSON( "http://www.reddit.com/r/pics.json?jsonp=?", function foo(data) { ...

The console is displaying a null value outside of the block, however, the correct value is returned when

I am having an issue where the first console.log() is not returning the correct value, but the second one is. Can anyone provide assistance with this problem? angular.module('resultsApp', ['ngCookies']) .config(['$qProvider&a ...

Using the same conditional statement on multiple pages within a Next.js application

I'm currently working on a project with Next.js and I've encountered an issue when fetching data from my server using the useSWR hook. There are certain conditions that need to be met in order to display specific content on the page, as shown in ...

The process of locating a textarea by its id becomes obsolete when integrating CKEDITOR

The data table has editable cells, where clicking on a cell will trigger a bootstrap modal to display with a textarea containing the text retrieved from the database. Snippet of the table structure: <table class="table table-striped table-hover" id="t ...

Removing the Yellow Highlight on Input Field Following Email Autocomplete in Chrome

My username-password form is styled and working perfectly, but there's an issue that arises when I log in multiple times. Chrome automatically fills in my email, turning the username textbox yellow. It doesn't seem to happen with Firefox or Safar ...

Exploring the Functionality of InputRef in Material UI Core Version 3.9.2

Encountering an issue in Material ui core version 3.9.2 When using inputRef={input => { this.input = input; }} An error is displayed: TypeError: Cannot set property 'input' of undefined If we replace this.i ...

Unusual occurrences of backslashes in arrays when using JSON.stringify

While experimenting with JavaScript, I observed an unusual behavior when inserting a backslash \ into a string within an array and using JSON.stringify() to print it. Normally, the backslash is used for escaping special characters, but what if we actu ...

Using Selenium to handle asynchronous JavaScript requests

Having recently started working with Selenium and JavaScript callback functions, I've encountered a problem that I can't seem to solve on my own. My issue revolves around needing to retrieve a specific variable using JavaScript. When I manually i ...

Angular does not delay for promises to settle

Issue I am facing is related to Angular not waiting for promises to be resolved. The console inspection reveals that the provider and skills objects are not retrieved before the promises are returned. I have included the key parts of the code below. The s ...

Is there a way to eliminate curly braces from JSON strings with a regular expression?

Hello, I am working with a JSON file and I need to manipulate the content of the chapters array. Specifically, I want to remove the curly braces from inside the strings but only if they contain more than three words (two spaces). Is it achievable using Reg ...

Can a Vue computed property return a promise value?

I have a specific computed property in my code that triggers an API request and retrieves the required data: async ingredients() { const url = "/api/ingredients"; const request = new Request(url, { method: "GET", credentials: "same-or ...

Surprising outcome experienced in the realm of React

After conducting an AJAX request, I'm storing the fetched data into the state variable. However, when I attempt to print it in the console using the provided code snippet, the array appears to be empty. state = { addressOject: [] }; view = valu ...

Typed NextJs navigation to a specific route

<Link href="/about"> <a>About Us</a> </Link> Is there a way to ensure type safety with NextJs links? Currently, it is challenging to restructure the Link component as it is just a string. I stumbled upon this repos ...

Tips for implementing PHP Instagram Signature using AJAX

I'm facing a challenge with the latest Instagram API, which now requires an Enforced Signed request that includes both an Access Token and Client Secret to generate a Signature. If anyone could spare some time to help me out, I would greatly apprecia ...

Using Angular promises and the $http service

ng.module('app') .service('CardService', ['$http', CardService]) function CardService($http) { this.$http = $http; var self = this; $http.get('http://localhost:3000/db').success(function(data) { ...

Developing a pop-up feature that triggers upon clicking for a miniature rich text editing

Looking to integrate the Tiny rich text editor into my code. Check out the TextEditor.js component below: import React from 'react'; import { Editor } from '@tinymce/tinymce-react'; class App extends React.Component { handleEditorCha ...