How can I implement MUI Autocomplete if the search term does not match the option label?

How can I filter the options in a Material UI Autocomplete component based on a property of the option value that is not displayed as the label? I want the user to be able to input an item id, like 5141, and have the options filtered to show 'brass pipes'.

const MyAutoComplete = () => {
    const [item, setItem] = useState()
    const [input, setInput] = useState('')

    const items = [
    { id: 5141, name: 'brass pipes', listPrice: 2.32 }, 
    { id: 214, name: 'bronze pipes', listPrice: 1.89 },
    { id: 3155, name: 'toilet seat ', listPrice: 5.61 }
    ]
    
    return (
        <Autocomplete
            options={items}
            getOptionLabel={(item) => item.name || ''}
            value={item}
            onInputChange={(e, v) => {
                setInput(v)
            }}
            isOptionEqualToValue={(option, value) => option.id === value.id}
            inputValue={input}
            onSelect={(e, v) => setItem(v)}
            renderInput={(params) => (
                <TextField {...params} label="items" variant="standard" />
            )}
        />
    );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Answer №1

In my opinion, utilizing the createFilterOptions function is the appropriate approach for achieving this task. By adjusting the stringify option, you can customize the desired output.

const filterOptions = createFilterOptions({
  stringify: (option) => option.name + option.id,
});

<Autocomplete filterOptions={filterOptions} />;

You can view a working example of this code in action using this codesandbox link.

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

Tips for effectively dividing a component's code into smaller sub-components

Within my component MyComp, there exists an extensive code that I wish to divide into 3 separate components. In envisioning the structure of MyComp, I am seeking general advice and a brief example in response: import React, { Component, Fragment } from & ...

Having trouble passing a React Router Link component into the MuiLink within the theme

The MUI documentation explains that in order to utilize MuiLink as a component while also utilizing the routing capabilities of React Router, you need to include it as a Global theme link within your theme. An example is provided: import * as React from & ...

When is it appropriate to utilize props and CSS in customizing Material UI components?

As a beginner with Material UI, I'm curious about when to use props within the .jsx script and when to utilize CSS in a separate stylesheet to style MUI elements. Is it necessary to still incorporate CSS stylesheets for MUI elements or is it preferabl ...

Access Firestore documents within the NextJS 13 framework

As a newcomer to React/NextJS, I am working on fetching a list of documents from a Firestore Collection using NextJS 13 in a SSR Page so that I can display them below. Although I have successfully retrieved the documents within my function, the challenge ...

Ways to specify the styles for tr, td, and label elements within a material table

Hey there! Currently, I'm working with material table in react. I came across this page: https://material-table.com/#/docs/features/styling, where it mentions that we can use cellStyle, headerStyle. But what if I want to add more detailed styles to e ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...

Customize the collapse direction of Mui Accordion

Currently, I have integrated the Mui Accordion component into my project. I am interested in exploring the possibility of customizing the opening direction of the Accordion. Is it feasible to have it open horizontally from the side instead of the default v ...

The onChange event was not able to be activated within the material-ui radioGroup component

Utilizing the RadioButton component to showcase different options of a question within a custom-built component: import FormControl from "@material-ui/core/FormControl"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Grid from " ...

Looks like there was an error with the start script for [email protected]

I am facing an error in my React application's client side directory where node_modules are installed. The app was working fine until 2 weeks ago, but now when I try to run 'npm start', it fails to launch. The error message in the terminal i ...

The Material-UI Style is malfunctioning, receiving a warning that the prop `className` does not match on the server

Having trouble with style not displaying correctly while using Material-ui with Next.js. Encountering the following warning: "Warning: Prop className did not match. Server:" I referenced the example for Next.js With Material-ui from here. Environmen ...

Can dynamic CSS imports be unloaded in a React application?

I am facing an issue with loading two files using react.lazy and suspense: import React, { Suspense, lazy } from "react"; import { Route, Redirect } from 'react-router-dom'; const MainLayout = lazy(() => import('Components/Layout/MainL ...

There appears to be an issue with the Material Ui modal not functioning properly within the full screen component

Currently, I am facing an issue with the react-full-screen node package as modals, popovers, and drawers are not functioning properly within my full screen component. Can anyone assist me in implementing a functional modal that works seamlessly with my fu ...

React JS - Cautionary Messages Encountered During Execution of the npm add gh-pages Command

I attempted to integrate gh-pages into my project, but unfortunately encountered some warnings that prevented me from completing the process successfully. Feel free to view the image link below for more information ...

Having difficulty running unit tests on a styled component that is overriding material-ui

In my project, I have a customized styled component for a navigation list item which is wrapped around a Material-UI list item. To override the default styles without using '!important' flags, I am utilizing the '&&' operator in ...

Is it possible to nest StylesProvider contexts?

Is it possible to create nested StylesProvider contexts in MUI, similar to how we can nest ThemeProvider contexts? I have a specific section of my application where I need to use custom className prefixes to avoid conflicts caused by hydration issues that ...

The given 'FC<ComponentType>' type argument cannot be assigned to the 'ForwardRefRenderFunction<unknown, ComponentType>' parameter type

Currently, I am using react in conjunction with typescript. Within my project, there are two components - one serving as the child and the other as the parent. I am passing a ref to my child component, and within that same child component, I am binding my ...

The React component that generates HTML is not rendering correctly

I have a function that generates an unordered list export const generateListMarkup = (data) => { var ul = document.createElement('ul') let labels = {Data1: 'Data 1 name', Data2: 'Data 2 name', Data3: 'Data ...

Tips for adjusting the wrapper css rule of a Tabs component to left-align text in a vertical tab within Material-UI

Typically, when text is placed inside the wrapper, it is aligned in the center. Is there a way to adjust the wrapper rule in <span class="MuiTab-wrapper">Item One</span> so that the tab text is aligned to the left (similar to what w ...

The fade effect in React and material ui is consistent across both elements

I am facing an issue with a list where, for each list sibling onclick, a different element fades in with different text. The problem occurs when the fade effect starts once on siblings in the list and then disappears, not enabling again. This is the code: ...

Choose a label that will consistently appear over the component, even if a value has already been selected

Utilizing Material UI v5 with emotion, I am in need of the component label to consistently cover the select, regardless of whether any values have been selected. Upon reviewing their documentation and conducting a Google search, it appears there is no str ...