Anshul
Anshul

Reputation: 23

How to show the selected value in input textfield in material ui autocomplete?

How can I show the selected option in the textField? What prop can I use?

The options are shown when clicked on the input field, but after selecting an option label, the selected text is not shown in the text field.

This is the code I'm working with:

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import CircularProgress from "@material-ui/core/CircularProgress";
import axios from "axios";

class AutoC extends React.Component {
  state = {
    value: "",
    open: false,
    options: []
  };

  getOptions = () => {
    this.setState({ open: true });
    const { options } = this.state;

    if (options.length > 0) {
      return;
    }

    // returns list of university names

    axios
      .post("/api/search", { search: "   " })
      .then(res => {
        this.setState({ options: res.data });
      })
      .catch(err => {
        console.log(err);
      });
  };

  render() {
    const { open, options, value } = this.state;
    const loading = open && options.length === 0;

    return (
      <div
        style={{ marginTop: "40px", display: "flex", justifyContent: "center" }}
      >
        <Autocomplete
          id="asynchronous-demo"
          style={{ width: 300 }}
          open={open}
          onOpen={this.getOptions}
          onClose={() => this.setState({ open: false })}
          getOptionLabel={option => option.Name}
          options={options}
          loading={loading}
          renderInput={params => (
            <TextField
              {...params}
              label=""
              fullWidth
              InputProps={{
                ...params.InputProps,
                endAdornment: (
                  <React.Fragment>
                    {loading ? (
                      <CircularProgress color="inherit" size={20} />
                    ) : null}
                    {params.InputProps.endAdornment}
                  </React.Fragment>
                )
              }}
            />
          )}
        />
      </div>
    );
  }
}

export default AutoC;

Upvotes: 2

Views: 1492

Answers (1)

Dmitry Dyudeev
Dmitry Dyudeev

Reputation: 26

I think I had the same issue. Fixed it by changing '@material-ui/core' and '@material-ui/lab' versions to latest in package.json.

Upvotes: 1

Related Questions