Incorporating a TextField in MUI Autocomplete for extended functionality

Within my React application, I have implemented a MUI Autocomplete field as a searchable dropdown. One of the options in this dropdown is a TextField, which should allow the user to input text.

The TextField renders correctly, but unfortunately, clicking on it does not activate it for typing.

Is there a way to enable users to select the TextField and start entering text without closing the Autocomplete list of options?

Edit based on feedback: The dropdown should closeOnSelect when choosing regular options.

https://i.sstatic.net/OlMZVj91.png

https://codesandbox.io/p/sandbox/65g99s

Alternatively, here is the code snippet:

import "./styles.css";

import { Autocomplete, TextField } from "@mui/material";
import { useState } from "react";

export default function App() {
  const [selectedOption, setSelectedOption] = useState("");
  return (
    <Autocomplete
      options={["Option 1", "Option 2", "Option 3"]}
      renderInput={(params) => <TextField {...params} />}
      renderOption={(props, option) => {
        if (option == "Option 3") {
          return (
            <li {...props}>
              <TextField onClick={(e) => e.stopPropagation()} />
            </li>
          );
        } else return <li {...props}>{option}</li>;
      }}
      value={selectedOption}
      onChange={(_, newValue) => {
        if (newValue) {
          setSelectedOption(newValue);
        }
      }}
    />
  );
}

Answer №1

  • Prevent event bubbling: Implement onMouseDown and onClick handlers to halt the propagation of the click event.
  • Avoid closing Autocomplete: Utilize the disableCloseOnSelect prop to ensure that clicking the TextField does not close the dropdown menu.

Sample Code :

import "./styles.css";
import { Autocomplete, TextField } from "@mui/material";
import { useState } from "react";

export default function App() {
  const [selectedOption, setSelectedOption] = useState("");
  const [inputValue, setInputValue] = useState(""); // Value of input in TextField

  return (
    <Autocomplete
      options={["Option A", "Option B", "Custom Choice"]}
      disableCloseOnSelect // Keep the menu open after selection
      renderInput={(params) => <TextField {...params} label="Choose an option" />}
      renderOption={(props, option) => {
        if (option === "Custom Choice") {
          return (
            <li {...props} onMouseDown={(e) => e.stopPropagation()}>
              <TextField
                value={inputValue}
                placeholder="Enter something here..."
                onChange={(e) => setInputValue(e.target.value)}
                onClick={(e) => e.stopPropagation()} // Prevent closing when clicking
                fullWidth
              />
            </li>
          );
        }
        return <li {...props}>{option}</li>;
      }}
      value={selectedOption}
      onChange={(_, newValue) => {
        if (newValue) {
          setSelectedOption(newValue);
        }
      }}
    />
  );
}

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

Issues with HTML5 drag and drop functionality seem to be causing problems

Check out this example I created: http://jsfiddle.net/NQQL6/ While dragging a link, the cart should turn green. Upon dragging the item over the cart, it should turn red. This functionality works fine when the cart is empty, but encounters issues otherwi ...

The exceljs function for downloading an Excel workbook is not activated by using the Post method

Presently, I am engaged in the development of a React and Node application. This app is designed to store data entries in a database, with the capability for users to download all stored data in an Excel workbook. To make this possible, I have integrated ...

The complexity surrounding various versions of jQuery, the .noConflict method, and the jQuery migrate feature

I was tasked with making a large-scale website responsive, and decided to utilize Bootstrap as the framework. However, I encountered issues due to the jQuery version (v1.8.2) being used. In my development environment, I resolved this by including the follo ...

Navigating within an ng-if or ng-show in AngularJS

Currently, I am developing a web application using AngularJS and there are times when I need to verify if the element inside the ng-if or ng-show directive belongs to a specific list. The approach I am using right now is shown below: <div ng-if="object ...

A Vue.js trick to modify the element's class within a v-for loop when hovering in and out

I'm having trouble changing the class of a single element within a v-for loop based on mouseenter/mouseleave events. I want only the hovered element to change its class, but currently, all elements in the list are affected. I attempted binding the cl ...

Modifying text appearance and design in material-ui release 0.15.4

I'm quite new to CSS and front-end web development, and I'm struggling with setting the style of a button on my page. I want to change the text color and possibly adjust the primary color of my theme from cyan to blue. I know that material-ui has ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

Is it possible to use multiple schemas for one collection name?

I am currently working on creating different schemas for a single collection, such as User or subUser. I aim to store both User and subuser data in the same collection but with different schemas. Here is an example of my schema file: export const AryaSchem ...

Is there a way to conceal the search bar within my Vue.js web app upon clicking a link within a child component?

In my component hierarchy, I have a child component called home-book-line: <template> <div> <div v-if="items && items.length > 0"> <nuxt-link :to="`/books/${item.id}`" @click="closeAndHid ...

Sending data from middleware to a function in Node.js is a crucial step in the communication

While working with express, I have a requirement to develop a middleware for validation purposes. The code snippet I have looks like this: Code: app.use('/upload', formData) app.use('/upload', function firstUpload(req, res, next) { ...

Unable to shake off a sudden burst of information following the ajax page load

I am facing an issue with my page that involves making different ajax calls based on user clicks. There are four IDs, and only one should be visible at a time. However, when new ajax content is loaded into a div, I experience a brief flash of the previou ...

Generate a separate list for every item within a JSON array

I am working with a JSON array that looks like this: [ { "id":"1", "0":"1", "name":"Quique", "1":"Quique" }, { "id":"2", "0":"2", "name":"Kety", "1":"Kety" } ] My goal is to extract the values of id and name from t ...

developing a custom geolocation feature in cordova to retrieve the current position

I recently explored Cordova Geolocation examples and I'm facing difficulty in understanding how to retrieve the position data from its function so that I can utilize it multiple times from various locations. Below is an illustration of retrieving the ...

Ongoing state configuration in a React hook

My custom hook: export function useToken2() { const { data: session, status } = useSession(); const [token, setToken] = useState<string | null>(null); useEffect(() => { if (status === 'authenticated' && session?.accessToken) { ...

Avoid putting the URL in the browsing history

After reviewing the browser history information, I realize that access to the array of history objects is restricted, making it impossible for me to delete them. However, my current objective is to prevent parameterized URLs from being added to the history ...

What is the best way to combine two JavaScript functions into a single function, especially when the selector and function to be invoked may differ?

In the provided snippet, I am using the following function callers: // del if ( maxDelivery > 0 ) { if ( maxDelivery === 1 ){ delAdressFunc( dels ); } else { for ( i = 0; i < maxDelivery; i += 1 ){ delAdressFunc( ...

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

Trouble loading CSS file in Vue library from npm package

When using vue-cli to build a library (npm package) that functions for both SSR and client-side, everything seems to be functioning correctly except for one issue; the CSS only loads if the component is present on the page being refreshed. However, when ac ...

Javascript code is not functioning properly (library missing?)

I recently upgraded my Bootply.com account in order to download a snippet that I believed would work perfectly. However, it seems like there's something missing here. Can anyone help me figure out what's wrong with the original Bootply.com snippe ...

How can I determine if any of the values in the array (both previous and current) are identical?

I am facing a challenge with 3 input fields that could potentially have the same values, but I need to ensure uniqueness for each field. {productFormData.Roles.map((role: string, index: number) => { return ( <div className={`form-group in ...