reactjsreact-nativematerial-uimui-autocomplete

AutoComplete Material UI React getOptionSelected prop not working


I am fairly new to react, and would really appreciate some pointers here:

I have an autocomplete dropdown with certain set of options. I want one of them to be selected by default, based on a condition I have.

from what i understand this can be completed by getOptionSelected prop in Autocomplete.

I created a sample to test this, however this is not working as expected. Can you please help?

CodeSandbox Here

/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option: { title: string; year: number }) => option.title}
      getOptionSelected={(option) => option.year === 1994}
      style={{ width: 300 }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 }
];

Solution

  • V5

    If you're updating to v5, getOptionSelected is renamed to isOptionEqualToValue. See the migration guide here.

    V4

    Use getOptionSelected only if you need to validate selected options, which may not be what you want here.

    If you want to change the selected option based on a condition, you can modify the value props of the Autocomplete component. In the demo below, you can change the selected option by specifying the option index in the TextField.

    export default function Demo() {
      // Use null instead of undefined to fix mixing uncontrolled and controlled error
      // https://github.com/mui-org/material-ui/issues/18173#issuecomment-552420187
      const [value, setValue] = React.useState(null);
      const onChangeOptionIndex = (e) => {
        const optionIndex = parseFloat(e.target.value);
        const selectedValue =
          top100Films.find((o, i) => i === optionIndex) || top100Films[0];
    
        setValue(selectedValue);
      };
    
      return (
        <Box display="flex">
          <TextField label="Option Index" onChange={onChangeOptionIndex} />
          <Autocomplete
            id="combo-box-demo"
            options={top100Films}
            onChange={(_, newValue) => setValue(newValue)}
            value={value}
            getOptionLabel={(option) => option.title}
            style={{ width: 300 }}
            renderInput={(params) => (
              <TextField {...params} label="Combo box" variant="outlined" />
            )}
          />
        </Box>
      );
    }
    

    Live Demo

    Edit Material-UI Autocomplete Default Value