How to handle change on Autocomplete component from React Material UI?

Sometimes, we want to handle change on Autocomplete component from React Material UI.

In this article, we’ll look at how to handle change on Autocomplete component from React Material UI.

How to handle change on Autocomplete component from React Material UI?

To handle change on Autocomplete component from React Material UI, we set the onChange prop of the Autocomplete to a function that has the value as the 2nd parameter.

And we can set the value prop to the state that we called the state setter function to set the value for.

For instance, we write:

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

const top5Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 },
  { title: "12 Angry Men", year: 1957 }
];

export default function App() {
  const [movie, setMovie] = useState(top5Films[0]);

  return (
    <div>
      <Autocomplete
        value={movie}
        options={top5Films}
        getOptionLabel={(option) => option.title}
        onChange={(event, value) => setMovie(value)}
        renderInput={(params) => (
          <TextField {...params} label="Label" variant="outlined" fullWidth />
        )}
      />
    </div>
  );
}

We have the top5films array which we use as the value of the options prop.

And we set the value to the movie state to show the selected value.

Next, we set the getOptionLabel to a function that returns the property value to show in the top5Films array.

Then we set the onChange prop to a function that calls setMovie with value to set movie to the selected option.

Finally, we set the renderInput to a function that renders a TextField to render the text field.

As a result, we see that ‘The Shawshank Redemption’ is set initially.

And when we select another choice, we see the selected choice displayed.

Conclusion

To handle change on Autocomplete component from React Material UI, we set the onChange prop of the Autocomplete to a function that has the value as the 2nd parameter.

And we can set the value prop to the state that we called the state setter function to set the value for.