How to clear mui autocomplete on click of button in react js?

Hi Friends ๐Ÿ‘‹,

Welcome To aGuideHub!

To clear mui autocomplete on click of button in React js, you have to use react state and when user select any option then you have to select value store in the react state. Now when user click on the button you have to set state value as an empty, thatโ€™s how you can clear mui autocomplete on click of button in react js.

Today, I am going to show you, how to clear mui autocomplete on click of button in react js.

Installation

Install the following packages to use clear mui autocomplete on click of button in react js.

npm

npm install @mui/material @emotion/react @emotion/styled

yarn

yarn add @mui/material @emotion/react @emotion/styled

MUI material clear mui autocomplete on click of button example.

The code below is an example of a Material UI autocomplete that is always open. You have to import @mui material autocomplete and use react state and when user select any option then you have to select value store in the react state. Now when user click on the button you have to set state value as an empty.

App.js

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

export default function App() {
const [value, setValue] = useState('');

  const handleClear = () => {
    setValue('');
  };

  return (
    <>
      <Autocomplete
        value={value}
        onChange={(event, newValue) => {
          setValue(newValue);
        }}

        sx={{ width: 300 }}
        options={['Option 1', 'Option 2', 'Option 3']}
        renderInput={params => (
          <TextField {...params} label="Combo box" variant="outlined" />
        )}
      />
      <Button onClick={handleClear} sx={{backgroundColor: `yellow`, border: `1px solid`
      }}>Clear</Button>
    </>
  )
}

In the above code example, I have used the @mui/material component and clear mui autocomplete on click of button in react js.

Check the output of the above code example.

React, Mui, button, clear

All the best ๐Ÿ‘

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts