Search code examples
javascriptreactjsreact-hooksmaterial-uiautocomplete

Create a button to clear MUI autocomplete


I am trying to create a button to clear MUI autocomplete value and delete data from the UI.

using the below code I am able to delete data from the UI but onChange value still in the autocomplete and I am trying to clear it by clicking Clear Data & Autocomplete button

How can I do that?

this image before clicking the button

this image before clicking the button

this image after clicking the button

this image after clicking the button

as you can see the onChange value still in the autocomplete and I want it to be cleared because I clicked Clear Data & Autocomplete button already

import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export default function ComboBox() {
  const [data, setData] = React.useState("");
  return (
    <>
      <Autocomplete
        disablePortal
        id="combo-box-demo"
        options={top100Films.map((movie) => movie.label)}
        onChange={(e, val) => setData(val)}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Movie" />}
      />
      <h1>{data}</h1>
      <button onClick={() => setData("")}>Clear Data & Autocomplete</button>
    </>
  );
}
const top100Films = [
  { label: "The Shawshank Redemption", year: 1994 },
  { label: "The Godfather", year: 1972 },
  { label: "The Godfather: Part II", year: 1974 },
  { label: "The Dark Knight", year: 2008 },
  { label: "12 Angry Men", year: 1957 },
  { label: "Schindler's List", year: 1993 },
  { label: "Pulp Fiction", year: 1994 }
];

Solution

  • You just need to make the Autocomplete a controlled input by settings it's value to your data state.

    <>
      <Autocomplete
        disablePortal
        id="combo-box-demo"
        options={top100Films.map((movie) => movie.label)}
        onChange={(e, val) => setData(val)}
        // Added value here
        value={data}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Movie" />}
      />
      <h1>{data}</h1>
      <button onClick={() => setData("")}>Clear Data & Autocomplete</button>
    </>;
    

    CodeSandBox : https://codesandbox.io/s/serene-snyder-1gxnlg?file=/demo.js