What is causing the TypeScript error in the MUI Autocomplete example?

I am attempting to implement a MUI Autocomplete component (v5.11) using the example shown in this link:

import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

const options = ['Option 1', 'Option 2'];

export default function ControllableStates() {
  const [value, setValue] = React.useState<string | null>(options[0]);
  const [inputValue, setInputValue] = React.useState('');

  return (
    <div>
      <div>{`value: ${value !== null ? '\'${value}\'' : 'null'}`}</div>
      <div>{`inputValue: '\${inputValue}'`}</div>
      <br />
      <Autocomplete
        value={value}
        onChange={(event: any, newValue: string | null) => {
          setValue(newValue);
        }}
        inputValue={inputValue}
        onInputChange={(event, newInputValue) => {
          setInputValue(newInputValue);
        }}
        id="controllable-states-demo"
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Controllable" />}
      />
    </div>
  );
}

Despite following the MUI example without modification, I encountered two typescript errors when using v4.7.4:

value

Type 'string' is not assignable to type 'string[]'.ts(2322)
useAutocomplete.d.ts(292, 3): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & AutocompleteProps<string, undefined, undefined, undefined, "div">'

onChange

Type '(event: any, newValue: string | null) => void' is not assignable to type '(event: SyntheticEvent<Element, Event>, value: string[], reason: AutocompleteChangeReason, details?: AutocompleteChangeDetails<string>) => void'.
Types of parameters 'newValue' and 'value' are incompatible.
    Type 'string[]' is not assignable to type 'string'.ts(2322)
useAutocomplete.d.ts(217, 3): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & AutocompleteProps<string, undefined, undefined, undefined, "div">'

It's puzzling because I have simply copied the code from the MUI example. Additionally, I expect the value to be a single string while the options are in an array format.

Update

To troubleshoot the typescript error, you can view the configuration in this Codesandbox.

Answer №1

To disable multiple selection, add multiple={false} in the Autocomplete component

  <Autocomplete
    multiple={false}
    value={value}
    onChange={(event: any, newValue: string | null) => {
      setValue(newValue);
    }}

View Demo

It's worth noting that by default, the multiple selection should be false, but in some cases it needs to be explicitly set to false in the code sandbox editor.

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

Using the textbox input to trigger an alert message

Just starting out with JavaScript and I'm attempting to create an alert box that not only displays the message "Thank You For Visiting" when you click the Enter button, but also includes the name entered into the text box. While I have successfully im ...

Identify the user's default character encoding in order to provide the appropriate CSV file

Is there a way for the website to automatically serve CSV files encoded as windows-1252 to users on Windows workstations, and encoded as UTF-8 to other users? Currently, two URL links are used which requires the user to decide which one to click. Most use ...

Is it possible to scope component styles instead of using inline styles in order to avoid being overwritten by multiple React applications on a single webpage?

My application contains the following HTML: <div id="react-root-navbar"></div> <div id="react-root-body"></div> Along with React components that utilize React.DOM.render on each div. Both React components utili ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Having trouble with Discord.js version 12 and the messageReactionAdd event not triggering properly?

client.on('messageReactionAdd', (reaction, user) => { console.log('If you see this I actually work...'); }); I am having some trouble with my code. Despite setting up a simple console log, it seems like the code is not running prope ...

A guide on accessing Textfield input values in Redux-form while utilizing MaterialUI

The objective is to retrieve input values from a material UI component and transmit them to an action creator within a handleSubmit function. <Field name='email' component={email => <TextField fullWidth autoComplete='off' clas ...

Maintaining consistent height using JavaScript

Dealing with equal height using just CSS can be a hassle, especially when you want to support older browsers like IE9. That's why I've decided to use JavaScript instead. If a user disables JavaScript, having unequal heights is the least of my con ...

Is the memory usage of node.js proportional to the number of concurrent requests, or is there a potential memory leak?

Running the following node.js code: var http = require('http'); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/plain'}); res.write("Hello"); res.end(); }).listen(8888); Upon starting the server ...

Error encountered while attempting to send SendGrid email to multiple recipients

Currently, I am using const sgMail = require('@sendgrid/mail'); with sendgrid version 7.6.2. Whenever I attempt to add two email addresses in an array and then pass it into either send() or sendMultiple(), an error is being thrown like below. st ...

Utilizing VueJS and Lodash: The technique for extracting an array of objects exclusively featuring a specific key string

I am attempting to extract certain data from an Object that has a string _new attached to it. Explore the code on Codesandbox: https://codesandbox.io/s/vibrant-bardeen-77so1u?file=/src/components/Lodash.vue:0-353 This is what my data looks like: data.j ...

Challenges of using react in conjunction with material UI

There is a hook error being displayed, even though I do not have any hooks in my code. This issue only arises when using Material UI. Interestingly, if I remove certain lines of code after the return statement, the error disappears. Here is the project co ...

Encountering issues while trying to establish a connection to MongoDB through JavaScript

I have developed a code for seamlessly integrating various social networking logins with nodejs. Below is my server.js file: // include the necessary tools var express = require('express'); var app = express(); var port = process.env ...

How can I resolve the Vue warning about an unknown custom element <password-input>?

I've been working on resolving an error within a component, but unfortunately, I'm still encountering issues. The error message is as follows: [Vue warn]: Unknown custom element: - have you registered the component correctly? For recursive co ...

Tips for integrating Stripe into a React test

I am currently conducting a test on a React component that utilizes Stripe, and I am unsure about the best way to structure the test. An error message has been popping up as follows: Error: In order to use react-stripe-elements, ensure that Stripe.js ( ...

Injecting Dependencies in Angular 2 Without Using the Constructor

Exploring DI in Angular 2 has led me to implement a REST-Client using generic subtypes for concrete Datatypes like this: class RESTClient<T>{ constructor() { var inj = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]); this. ...

Encountered an issue in React Native/Typescript where the module 'react-native' does not export the member 'Pressable'.ts(2305)

I have been struggling to get rid of this persistent error message and I'm not sure where it originates from. Pressable is functioning correctly, but for some reason, there is something in my code that doesn't recognize that. How can I identify t ...

Button appears and disappears sporadically while browsing in Safari

I created a slider using SCSS, JavaScript, and HTML. You can view the demo at this link: https://jsfiddle.net/rr7g6a1b/ let mySlider = { initializeSlider: function (options) { let slider = options.container; let slides = slider.querySelectorAll( ...

The openapi-generator with the typescript-angular language option appears to be experiencing some issues

I am facing issues with generating angular code using the openapi-generator for language typescript-angular. Do you have any suggestions on how to resolve this? I have already tried running openapi-generator help meta and it seems that -l is a valid option ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...

Is there a way I can create a slight gap between the icon and the text in this area?

After learning Reactjs and JavaScript, I have encountered a problem that I need advice on. In the image provided, the "Sign in" text does not have proper spacing between the icon and the text, unlike the other menu items. https://i.stack.imgur.com/b663b. ...