How can I show the text name as a selection in the React Material UI Autocomplete component while sending the ID as the value?

Material UI Autocomplete component functions properly, but I am interested in extracting object.id as the value for the onSelect event (rather than object.name). Essentially, I want to display the object.name as the select item label, while retrieving object.id as the onSelect event value (event.target.value). Currently, my event.target.value is identical to the select item label (object.name). Here is an example snippet from the Material UI documentation:

The options object looks like this:

const options = [
  { id: "01", name: "Peter" },
  { id: "02", name: "Mary" },
  { id: "03", name: "John" }
]

The Autocomplete setup mirrors that of the Material UI documentation:

<Autocomplete
      id="asynchronous-demo"
      fullWidth
      open={open}
      onOpen={() => {
        setOpen(true)
      }}
      onClose={() => {
        setOpen(false)
      }}
      getOptionLabel={(option) => option.name}
      options={options}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Asynchronous"
          variant="outlined"
          onChange={(event) => {
            if (event.target.value !== '' || event.target.value !== null) {
              onChangeHandle(event.target.value)
            }
          }}
          onSelect={(event) => {
            onSelectHandle(event)
          }}
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {loading ? (
                  <CircularProgress color="inherit" size={20} />
                ) : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      )}
    />

With the current setup, onSelect always returns object.name as event.target.value, however, I aim to send back object.id instead.

Is there a solution to achieve this?

Answer №1

Make sure to use Autocomplete's onChange method instead of TextField's onSelect when retrieving values.

<Autocomplete
    ...
    onChange={(event, newValue) => {
        onSelectHandle(newValue)
    }}
    renderInput={(params) => (
        <TextField
            {...params}
            label="Asynchronous"
            variant="outlined"
            onChange={(event) => {
                if (event.target.value !== '' || event.target.value !== null) {
                    onChangeHandle(event.target.value)
                }
            }}
            ...
        />
    )}
/>

To learn more, refer to the controllable states section in the Autocomplete documentation.

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

The React Testing Library encountered an error: TypeError - actImplementation function not found

Encountering a TypeError: actImplementation is not a function error while testing out this component import React from 'react'; import { StyledHeaderContainer, StyledTitle } from './styled'; export const Header = () => { return ( ...

Incorporated asynchronous functionality, struggling to integrate it into the code

Previously, I used to utilize the following code for handling state: //get state MyClass.prototype.getState = function(key) { var value; switch(this._options.type){ case "cookie": value = $.cookie(key); ...

Spontaneously generating visuals that lead an unpredictable existence

Every 0-2 seconds, I generate a unique image and place it randomly within a designated area. setTimeout("addImage()", Math.floor((Math.random() * 2000) + 1)); To maintain order, I want these images to vanish after being visible for an interval o ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

The parameter of type 'never' cannot be assigned with the argument of type 'number | boolean | undefined'

In my project, I am creating a validation input using TypeScript in Next.js. interface InputRules { required?: boolean min?: number max?: number minLength?: number maxLength?: number } I have defined an object that contains methods to handle val ...

Each time Firebase retrieves an object, it comes back with a unique name

One query has been bothering me: const questionsRef = firebase .database() .ref('Works') .orderByChild('firebaseKey') .equalTo(this.props.match.params.id); It's functional, but the issue lies in the output: "-LDvDwsIrf_SCwSinpMa ...

Tips for inserting a Google Play Store button within a ReactJS project

Looking for assistance in adding a Google Play Store button to my website. Currently using ReactJS and Material-UI, but struggling to find guidance online. As a beginner in ReactJS, any help would be greatly appreciated! ...

Tips for building a responsive dropdown menu using data from a database query

Currently, I am fetching a list of companies from Firestore and attempting to display them as options in a dropdown menu. While the companies state is being populated correctly from Firestore, the options are not being created or updated dynamically. How c ...

Finding and identifying specific text within Paper Material-UI can be achieved through a few

I have been attempting to vertically center the text inside a Paper component from material-ui. Below is my code: const style = { height: 150, width: 150, margin: 20, textAlign: 'center', rounded: true }; render () { ...

Develop a wrapper function to verify the user's role within the routes of the App.js component

I have a question that may seem quite broad, but I am struggling to find the right terms and methods to search online for guidance. My issue involves an app where users log in and are assigned a user role (such as admin or standard user). I need to restric ...

Tips for activating this effect even when the window is resized during page scrolling

There's a code snippet that enables the header to become unfixed when a specific div reaches the top of the screen and then scrolls with the rest of the content. While this solution works perfectly, I encountered a problem where the calculations for ...

Error in custom class using vanilla JavaScript: "Error: Unable to assign innerHTML to an undefined property"

Apologies for the ambiguous title, but I am struggling to pinpoint the exact issue at hand... I'm essentially guessing my way through this problem. This marks my initial venture into creating a reusable Javascript class. Below is a simplified version ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

React.js: The specified element type is not valid:

I am currently working on a sample project using react.js in Visual Studio 2019 Here is my Index.js file: import 'bootstrap/dist/css/bootstrap.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provi ...

What steps should I take to ensure my API secret remains secure during my next.js deployment?

Recently, I created a small internal application using React and Next.js. To keep my API key and secret secure, I followed the instructions on how to use an .env file provided by Next.js. In my api/hello.js file, I have a simple request that looks like th ...

Transform inline styles in React to CSS declarations

Is there a tool available that can convert React inline style descriptions into CSS rules? For example: { minHeight: 200, position: 'relative', flexGrow: 1, flexShrink: 1, display: 'flex', flexDirection: ' ...

In react-native, both the parent and child components are rendered at the same time

One of my components, the parent one, goes through an array of chapters and for each item found, renders a child component called 'ExercisesList' and passes an array of exercises to it. class ExercisesScreen extends Component { displaySelected ...

if else statement fails to work in ajax-based login form

I tried to create the code below by referencing processes.php, submit form, and ajax from various sources on the internet. However, my code doesn't seem to be working properly. proccess.php <?php session_start(); ini_set('display_errors&apos ...

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

Can someone help me figure out this lengthy React error coming from Material UI?

Issues encountered:X ERROR in ./src/Pages/Crypto_transactions.js 184:35-43 The export 'default' (imported as 'DataGrid') could not be found in '@material-ui/data-grid' (potential exports include: DATA_GRID_PROPTYPES, DEFAULT ...