How to clear mui autocomplete on click of button in react js?
January 21, 2023Hi 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.
All the best ๐