27

When passing an empty string to Autocomplete, it throws a console warning saying that the value is invalid.

How do I get this warning to go away? It doesn't cause any issues, but it extremely annoying to have this thrown in the console for every rerender. The only way I seem to get it to not happen is setting the initial value for the field as null, which in my understanding is not what I should be putting as a default value of an input.

Current Behavior 😯

When passing the default value of empty string to the Autocomplete component, it throws a console warning that the value empty string is invalid.

errorForGithub

Expected Behavior 🤔

If the value given to the Autocomplete is an empty string, there should be no warning or errors thrown.

Steps to Reproduce 🕹

Here is a link to showcase the error: https://codesandbox.io/s/material-demo-n0ijt

1) Pass an empty string to the value property of Autocomplete component.

3
  • Please update your question and remove all the non-relevant things. This is a copy&paste from the issue template of the material-ui github page. Please don't use this here in stackoverflow. Commented Apr 15, 2020 at 0:00
  • Seemed like a good way to show what I have done and what the issue I'm experiencing is. Commented Apr 15, 2020 at 0:08
  • As mentioned - keep only the relevant data (the structure is not relevant, the environment is not relevant, etc...) Commented Apr 15, 2020 at 0:14

7 Answers 7

43

you can use null as initial state and that might achieve what you're trying

value={data.value || null}

if you set it to undefined it complains about controlled component, this way I don't get an error even after I use the Autocomplete

Sign up to request clarification or add additional context in comments.

3 Comments

doing const val = [val, setVal] = useState(null); worked perfectly when I did value={val}
In MUI 5+, either this or isOptionEqualToValue={(option, value) => value === option || value === ''} solution can be used
I think this should be the accepted answer. It works (at least in my use-case) -- it silences the annoying complaint. It does not require passing other more complicated props to Autocomplete. Last, but not least, it has the most upvotes.
13

I solved it handling the case in which the input string is empty (you are not doing that). 3 things are needed in your Sandbox:

  1. line 17, inside the getOptionSelected, you must return true when the value is the empty string; in this way React selects one option and the warning disappears.
  2. line 14, modify the getOptionLabel, handling the case of the empty string. I would do the following:
getOptionLabel={option => option.title ? option.title : ''}

So in case the option has a title, it returns a title, otherwise it returns an empty string that is visualized.

  1. Finally, modify the onChange to handle the empty string, in this way
onChange={(e, selectedObject) => {
    if (selectedObject !== null)
        setValue(selectedObject)
}}

Overall:

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function FreeSoloCreateOption() {
  const [value, setValue] = React.useState("");

  return (
    <Autocomplete
      value={value}
      id="empty-string-demo"
      options={top100Films}
      getOptionLabel={option => option.title ? option.title : ''}
      getOptionSelected={(option, value) => {
        //nothing that is put in here will cause the warning to go away
        if (value === "") {
          return true;
        } else if (value === option) {
          return true;
        }
      }}
      onChange={(e, selectedObject) => {
        if (selectedObject !== null)
            setValue(selectedObject)
      }}
      renderOption={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField
          {...params}
          label="Default Value of Empty String"
          variant="outlined"
        />
      )}
    />
  );
}

5 Comments

Thanks! For my case just the label formator was causing the issue. Updated it to getOptionLabel={(option) => (option && option.label)? option.label: ""}
This is what I do: getOptionLabel={option => option?.title || ''} getOptionSelected={(option, value) => value === '' || option.id === value.id}
I have tried the above solution. When component initialising, all the options in dropdown are in selected mode.Can I get the fix for that ?
This one helped me a lot , i was in the exact same situation. Thank you!
I tried this, and it worked, but I was then having issues where all the options where highlighted in the autocomplete dropdown
0

One simple change is to filter the initial reset out

onChange={(event, newValue, reason) => {
    if (reason === 'reset' && newValue === '') {
        // Do nothing
    }
    else {
        setValue(newValue);
    }
}}

Comments

0
  <Autocomplete className={styles['vacation-list-status']}
                        id="vacation-list-status"
                        options={vacationStatus}
                        getOptionLabel={option => option.label}
                        onChange={(event, newValue) => {
                          handleVacationStatus( 
                              newValue ? newValue.value : null
                          );
                        }}
                        renderInput={(params) => (
                           <TextField
                            {...params}
                            variant="outlined"
                            label={t('status')}
                           />
                        )}
                    />

Comments

0

Add this to your Autocomplete...

isOptionEqualToValue={(option, value) => {
    // Accept empty string
    if(value === option || value === "") { return true; }
}}

2 Comments

this doesn't work. if the value is "" it will return true that every option is selected... It works if you reverse the lazy evaluation... if(value === option || value === "" ) { return true; }
user10233170 THANKS!!!
0
import * as React from "react";
import { Autocomplete, Button, TextField } from "@mui/material";

const options = ["alpha", "beta", "gamma", "delta", "epsilon"];

const Demo = () => {
  const [value, setValue] = React.useState(null);
  const handleReset = () => {
    setValue(null);
  };
  const handleChange = (event, value) => {
    setValue(value);
  };
  return (
    <>
      <Autocomplete
        id="combo-box-demo"
        freeSolo
        value={value}
        options={options}
        sx={{ width: 300 }}
        onChange={handleChange}
        renderInput={(params) => (
          <TextField {...params} label="Select an option..." />
        )}
      />
      <Button onClick={handleReset}>Reset</Button>
      <div>The current value is: {value}</div>
    </>
  );
};
export default Demo;

If you have multiple autocomplete and want to reset you can do this additionally, Pass value={value || []}. After reset u will have empty value

Comments

0

Your model should have this type:

key: string | null;

With default value:

key=null

And this weird cast:

<Autocomplete value={key as string | undefined}

This is the simplest way I found to eliminate the warning. ("@mui/material": "^5.16.7")

It sad that MaterialUI AutoComplete is not following the same behaviour as Select.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.