MUI Autocomplete Get and Set Values, Default Values, and Add Options

The MUI Autocomplete component is great for giving users limited options to choose from in forms or other UI layouts. I will show how to get and set values, including default values, in the Autocomplete component.

I will show how to use the Autocomplete’s data in a state value and also with a form submission. Finally, I will show how to add new values to the Autocomplete’s dropdown list.

We will create the Autocomplete form and Buttons in this screenshot:

Get and Set Values in MUI Autocomplete
Get and Set Values in MUI Autocomplete

The Resources section has full React tutorial code.

See a video version of this post on YouTube or watch below:

MUI Autocomplete Get Selected Value

There are two use cases where we want to get the selected value in an Autocomplete component:

  • For use in the UI (need a state value)
  • For form submission

If we create a state value and update it when the Autocomplete’s value changes, then we can use that value in other components. Here’s the code (with TypeScript):

const [acValue, setACValue] = useState<shipData | null>(data[0]);

<Autocomplete
  onChange={(event, value) => setACValue(value)}
/>

I used the onChange handler to pass the selected option to the state value’s setter.

If we want to get the Autocomplete’s selected value for use with a form submission, we only need to wrap the Autocomplete in a form element and add a Button with type="submit".

I added the state value to the handleSubmit so that we can log both values and see the difference. Here’s the code:

//JSX
<form onSubmit={(event) => handleSubmit(event, acValue)}>

const handleSubmit = (event: React.FormEvent<HTMLFormElement>, stateVal: shipData | null) => {
  event.preventDefault();
  console.log(event);
  console.log(stateVal);
};

If you want to log or test the values passed to a form submit, remember to add a preventDefault() call. This stops the submission network call and refresh.

Take a look at the two objects logged:

MUI Autocomplete Form Submit
MUI Autocomplete Form Submit

The first is the change event, and nested in that is target which has the elements with their values. We can get the string value of the Input component (part of Autocomplete) from this.

The second value is the state value, and it is an object.

MUI Autocomplete Set Value

The MUI Autocomplete has a couple of props for dynamically setting and controlling the component value. However, we need to be careful which one we choose to use.

  • inputValue only sets a value for the Input component
  • The value prop sends the passed value through getOptionLabel and compares with the options list.

Between these two, use the value prop. The inputValue prop may produce unexpected behavior.

To dynamically update the value, pass a state value to the value prop. I used the state const from the previous section: <Autocomplete value={acValue} />

If you don’t need a dynamically updating value, then I recommend using defaultValue which is described below.

MUI Autocomplete Default Value

If you need to set the initial value for your Autocomplete component and then never programmatically update it again, the best option is the defaultValue prop.

This prop accepts a value that only gets rendered until an option is selected from the Autocomplete’s dropdown list. When TypeScript is enabled, this prop also enforces consistent typing with the options list data.

Here’s example code where I pass a state value to defaultValue:

<Autocomplete defaultValue={acValue} />

My acValue is of type {  name: string;  manufacturer: string;}. I tried to pass a simple string to defaultValue and the compiler complained. This is good protection against bugs!

MUI Autocomplete defaultValue
MUI Autocomplete defaultValue

Here’s how to set default values in MUI’s TextField.

MUI Autocomplete Add New Option

We can add a new option to the options array simply by pushing to the array.

In my example I added a Button with an onClick handler that pushes a new item to the options data array. Here’s the click handler:

onClick={() => { data.push({ name: "Test Ship", manufacturer: "Test Manufacturer" }); }}

The new item was detected by the dropdown list the next time I opened the list:

MUI Autocomplete Add New Option
MUI Autocomplete Add New Option

TypeScript ensured that the new option was the proper type for the list, which meant I wouldn’t have any bugs in getOptionLabel if the new option was selected.

Resources and Related Links

Here’s how to customize the MUI Autocomplete component.

Here’s how to style the Material-UI Autocomplete component.

Here’s how to set multiple values programmatically in Material-UI’s Autocomplete component.

Here’s how to Use and Remove the MUI Autocomplete Clear Button

Here’s how to clear the TextField and Input components.

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

interface shipData {
  name: string;
  manufacturer: string;
}

const handleSubmit = (event: React.FormEvent<HTMLFormElement>, stateVal: shipData | null) => {
  event.preventDefault();
  console.log(event);
  console.log(stateVal);
};

export default function ValueAutocomplete() {
  const [acValue, setACValue] = useState<shipData | null>(data[0]);
  return (
    <form onSubmit={(event) => handleSubmit(event, acValue)} style={{border: '1px solid gray', borderRadius: '4px', padding: '16px'}}>
      <Autocomplete
        onChange={(event, value) => setACValue(value)}
        options={data}
        id="autocomplete-1"
        getOptionLabel={(option) => `${option.name}: ${option.manufacturer}`}
        renderInput={(params) => {
          return (
            <TextField
              {...params}
              variant="outlined"
              label="Name: Manufacturer"
            />
          );
        }}
        defaultValue={acValue}
        sx={{ mb: 2, minWidth: 400 }}
      />
      <Stack display="flex" justifyContent="space-around" direction="row">
        <Button
          variant="outlined"
          onClick={() => {
            data.push({ name: "Test Ship", manufacturer: "Test Manufacturer" });
          }}
        >
          Add Option
        </Button>
        <Button type="submit" variant="outlined">
          Submit
        </Button>
      </Stack>
    </form>
  );
}

const data = [
  {
    name: "CR90 Corvette",
    manufacturer: "Corellian Engineering Corporation",
  },
  {
    name: "Star Destroyer",
    manufacturer: "Kuat Drive Yards",
  },
  {
    name: "Sentinel-class landing craft",
    manufacturer: "Sienar Fleet Systems, Cyngus Spaceworks"
  },
];

MUI Autocomplete API Docs

Share this post:

4 thoughts on “MUI Autocomplete Get and Set Values, Default Values, and Add Options”

  1. Hi, nice write up. It helped me comprehend MUI Autocomplete better. I have a little challenge. I populate the dropdown with data from an endpoint. From the dropdown, I need to get only the values I SELECTED (checked) and make a post request. How best do i target the selected (checked) values and post or display.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.