Creating a feature to display an error message when duplicate values are detected with Autocomplete in MUI React

I'm currently facing a challenge with managing and notifying the user about setting a duplicate value. By default, if a user tries to input a value that already exists in the list, the "tag" won't be added. While this functionality works for me, I also want to display a warning message near the input field indicating that duplicate values are not allowed...

    <Autocomplete
      PaperComponent={CustomPaper}
      onChange={(event: any, newValue: string[], reason: string) => {
        handleInputUsersChange(event, newValue, reason);
      }}
      autoComplete
      freeSolo
      fullWidth
      multiple
      id={props.id}
      value={props.initEmails}
      options={listUsers.map((item) => {
        return item.name;
      })}
      renderInput={(params) => {
        return (
          <div ref={params.InputProps.ref} style={{ display: 'flex' }} data-test="test-div-autocomplete-comp">
            <TextField {...params} style={{ width: '1200px' }} />
          </div>
        );
      }}
    />

I am attempting to capture the validation or event used by Autocomplete to prevent adding duplicate tags, but so far I have been unsuccessful...

Thank you in advance!

Answer №1

MUI lacks a validation hook, so the workaround is:

  const initEmails = ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204a414e450e444f4560474d41494c0e434f4d">[email protected]</a>"];
  const [emails, setEmails] = useState(initEmails);

  const [duplicateEmailError, setDuplicateEmailError] = useState(false);

  const listUsers = [
    { name: "John Doe", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13797c7b7d3d777c7653747e727a7f3d707c7e">[email protected]</a>" },
    { name: "Jane Doe", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="593338373c773d363c193e34383035773a3634">[email protected]</a>" },
  ];

  return (
    <Autocomplete
      PaperComponent={Paper}
      onChange={(event, newValue) => {
        setEmails(newValue);
      }}
      onKeyUp={(event: React.KeyboardEvent<HTMLInputElement>) => {
        if (
          event.key === "Enter" &&
          listUsers.some((item) => item.email === (event.target as HTMLInputElement).value)
        ) {
          setDuplicateEmailError(true);
        } else {
          setDuplicateEmailError(false);
        }
      }}
      autoComplete
      freeSolo
      fullWidth
      multiple
      value={emails}
      options={listUsers.map((item) => {
        return item.name;
      })}
      renderInput={(params) => {
        return (
          <div ref={params.InputProps.ref} style={{ display: "flex" }} data-test="test-div-autocomplete-comp">
            <TextField
              {...params}
              style={{ width: "1200px" }}
              error={duplicateEmailError}
              helperText={duplicateEmailError ? "Duplicate Email" : null}
            />
          </div>
        );
      }}
    />
  );

Note the setDuplicateEmailError state and the validation against the listUsers in the onKeyUp prop.

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

A Guide to Effortlessly Implementing moment.js into a React TypeScript Application

I'm attempting to implement code splitting and one of the specific packages I want to separate into its own chunk is moment.js. Here's how I'm doing it: const myFunc = async (currentNumber) => { const moment = (await import('momen ...

Clearing the redux store when a User Logs Off

I am currently developing a fitness app and I have encountered a problem that seems like it should be easy to fix, but I just can't figure it out. The issue arises when User 1 logs out and User 2 logs in - User 2 ends up seeing User 1's workout ...

What steps are involved in setting up a React app on a server?

I'm in the process of figuring out how to deploy my react app online. Up until now, I've been running it on my mac using npm start, and accessing it through localhost:3000 or http://127.0.0.1:3000. Recently, I purchased a small server, installe ...

What is preventing useEffect from accessing my state variable within a return statement?

I'm struggling to figure out why my useEffect() React function is unable to access my Component's state variable. My goal is to create a log when a user abandons creating a listing in our application and navigates to another page. I've imple ...

Creating Styles in Material-UI using makeStyles: Tips for Styling by Element Name

I am currently facing a challenge of adding a rule for all <p> tags within the current component. Despite searching through various sources such as material-ui documentation and Stack Overflow, I have been unable to find any information on how to add ...

What is the process for adding a class to a number within an array?

Create an array with the values [1,0,1,0]. When displaying this array on a webpage, each element should be placed inside a div. If the element is 1, give the div a class of white; if it's 0, make it black. let state = { array2: [1, 0, 1, 0] }; } ...

Can someone guide me on the process of opening and closing a Material-UI Dialog within a Meteor/React application?

I'm attempting to create a dialog with a form that pops up when the user clicks a button. I followed the example on the Material-UI Dialog site for creating a button to open the dialog and adding a TextField within it. This is being done using Meteor ...

Guide on transforming headless wordpress href to a <Link> tag

I am currently working on a project using Next.js with the WordPress API, also known as headless WordPress. In my application, I am displaying content from a Gutenberg area which includes text and links. However, a problem I have encountered is that the li ...

Issue with React Context: The type 'Dispatch<SetStateAction<GiftsType>>' cannot be assigned to type '(arr1: string[], arr2: string[]) => void'

I'm currently working on a project in React+TS where I need to create a context that takes two string arrays and updates an object's state with these arrays. I keep encountering a title typo error in the setChoices function inside the return stat ...

Invoke a handler from one function within another function

I am unsure of the best approach for achieving this, or if it is even feasible, but I have two components: a main navigation bar (NavBar) that spans across the top of the page, and a sidebar drawer. NavBar: export default function NavBar() { const c ...

Why does the API in Next Js get triggered multiple times instead of just once, even when the strict mode is set to false?

React Query Issue I am currently facing an issue with React Query where the API is being triggered multiple times instead of just once when the selectedAmc value changes. I have tried setting strict mode to false in next.config.js, but that didn't so ...

Tips for personalizing the MUI Autocomplete filter using createFilterOptions

I am currently exploring the Autocomplete MUI component and trying to understand its functionalities. Initially, my basic implementation worked smoothly as expected with the provided code: import Autocomplete from '@mui/material/Autocomplete'; im ...

"Enhancing User Authentication with Firebase Email Verification in React Native

Does Firebase have a feature that allows me to verify if an email confirmation has already been sent to a user? I am able to check validation, but I need to determine whether the verification email has already been sent in order to decide if it needs to be ...

Tips for aggregating the values of object arrays in React props

I need help sorting three top-rated posts. Currently, the function displays three post titles along with their ratings, but they are not sorted by best rating. Can anyone assist me with this issue? {posts.slice(0, 3).sort((a, b) => ...

Modifying the Button style in the KeyboardDatePicker component from Material UI

I recently developed a website using Material UI, where all buttons are styled as "outlined" except for the Calendar in KeyboardDatePicker. The "ok" and "cancel" buttons in this dialog have the default appearance. After reviewing the API documentation (), ...

Retrieving Data from Class Component in a Functional Component using React

I am currently utilizing a React module called react-semantic-ui-datepickers, which I believe is built upon react-datepicker. Nonetheless, this is more of a general React query. In my file, I have both my main class component and the date picker functional ...

Is there a way to prevent Material-UI SpeedDial from automatically closing when a SpeedDialAction button is clicked?

Looking to customize the functionality of Material-UI's SpeedDial component (https://material-ui.com/api/speed-dial/). At present, when a SpeedDialAction is clicked, the main SpeedDial component automatically closes. I want to modify this behavior s ...

I am unable to assign inputProps with a numeric type for MuiOtpInput within Mui OTP Input

I've been trying to make use of the inputProps prop in combination with the MuiOtpInput component provided by the mui-one-time-password-input library. Specifically, I have configured the inputMode attribute to be "numeric" for each input fie ...

Using Redux Form to Access References in a Child Component

Recently, I started working with redux-form along with react-select. Within my redux-form, there is a child component that contains a element, which in turn renders a react-select component. My goal is to figure out how I can pass a reference to this com ...

Issue "Value of type '{}' cannot be assigned to parameter of type 'T | (() => T)'" encountered within a React component containing a type parameter

Currently, I am attempting to achieve the following: function SomeComponent<T>({ children }: PropsType) { const [configuration, setConfiguration] = useState<T>({}) } However, I am encountering this issue: The argument of type '{}&apos ...