How to get the value in the React Material-UI autocomplete?

Sometimes, we want to get the value in the React Material-UI autocomplete.

In this article, we’ll look at how to get the value in the React Material-UI autocomplete.

How to get the value in the React Material-UI autocomplete?

To get the value in the React Material-UI autocomplete, we can get the selected values from the onChange callback.

For instance, we write:

import React 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() {
  return (
    <div>
      <Autocomplete
        options={top5Films}
        getOptionLabel={(option) => option.title}
        onChange={(event, value) => console.log(value)}
        renderInput={(params) => (
          <TextField {...params} label="Label" variant="outlined" fullWidth />
        )}
      />
    </div>
  );
}

We add the Autocomplete from the @material-ui/lab module.

And we set the options prop to the top5films array to add the options for the autocomplete.

Next, we set getOptionLabel to a function that returns the title property from the object in the options array prop.

To get the value that we selected, we set the onChange prop to a function with the value parameter in the 2nd position.

Finally, we set the render component to a function that renders a TextField to render the input box for the autocomplete.

We spread the params as props of the TextField.

And we set the label and variant to the values we want.

As a result, when we select a value, we should see the selected object in the top5films array logged.

Conclusion

To get the value in the React Material-UI autocomplete, we can get the selected values from the onChange callback.