Skip to content
Related Articles

Related Articles

How to add function to the clear button icon in Material UI Autocomplete ?
  • Difficulty Level : Medium
  • Last Updated : 22 Feb, 2021

In this article, We are going to add an extra function to the clear button of Material UI Autocomplete. Take Reference to the clear button in code and then add a click event listener on it.

Creating React Application And Installing Module:

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder, i.e., folder name, move to it using the following command:

cd foldername

Step 3: Install required modules



npm install @material-ui/core
npm install @material-ui/lab

Project Structure: 

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

App.js




import React,{ Component }  from 'react';
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
  
class App extends Component {
  
  constructor(props) {
    super(props);
    this.state = {
      list: [
        { title: "Title 1"},
        { title: "Title 2"},
        { title: "Title 3"},
        { title: "Title 4"},
      ]
    }
  }
  
  componentDidMount(){
      // Take the Reference of Close Button
    const close = document.getElementsByClassName(
      "MuiAutocomplete-clearIndicator"
    )[0];
      
    // Add a Click Event Listener to the button
    close.addEventListener("click", () => {
      alert("Add your Own Functionality Here...");
    });
  }
  
  render() {
    return (
      <Autocomplete
        options={this.state.list}
        getOptionLabel={(option) => option.title}
        style={{ width: 300 }}
        renderInput={(params) => (
          <TextField {...params} label="Combo box" variant="outlined" />
        )}
    />
    );
  }
    
}
  
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :