Handling onChange Event for Material-UI Autocomplete Component in React Functional Components

Dec 02, 2025 · Programming · 9 views · 7.8

Keywords: React | Material-UI | Autocomplete | onChange

Abstract: This article explains how to use the Material-UI Autocomplete component in React functional components, handling the onChange event to save input tags to state. It details the event signature, implementation methods, and provides code examples.

Introduction

In React applications, the Material-UI Autocomplete component is commonly used for tag input functionality. Users may encounter issues handling the onChange event, especially when using functional components. This article explains in detail how to correctly use the onChange event to capture and save tag data.

Core Concepts

The onChange event receives two parameters: event and value. Here, value represents the currently selected value, which is an array in multiple mode. In functional components, the useState hook can be used to manage state.

Code Example

Below is an example code using functional components:

import React, { useState } from 'react';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField from '@material-ui/core/TextField';

function TagsInput() {
  const [tags, setTags] = useState([]);

  const handleChange = (event, value) => {
    setTags(value);
    console.log('Current tags:', value);
  };

  const options = [
    { title: 'Option 1', id: 1 },
    { title: 'Option 2', id: 2 },
    // more options
  ];

  return (
    <div style={{ width: 500 }}>
      <Autocomplete
        multiple
        options={options}
        getOptionLabel={(option) => option.title}
        onChange={handleChange}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="outlined"
            placeholder="Enter tags"
            margin="normal"
            fullWidth
          />
        )}
      />
    </div>
  );
}

export default TagsInput;

Conclusion

By correctly using the onChange event and the useState hook, you can effectively handle tag input with Material-UI Autocomplete in React functional components. Ensure understanding of the event parameters and adjust the code as needed for specific application scenarios.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.