T Hus
T Hus

Reputation: 51

How would i get the selected from my autocomplete box using material ui library in react

Below is the code which uses an external library called material ui and implements a search box with autocomplete. when a value is selected a input tag gets created and has value:"selected value", how would i access the value to be able to do something with it.

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

class ContractsList extends React.Component {
  render() {
    const contracts = this.props.contracts;
    return (
      <div>
        <div className="searchbar">
          <h1>All Aboard</h1>
        </div>
        <div className="search-bar">
          <Autocomplete
            id="search-bar-id"
            disableClearable
            options={contracts.map(contract => contract.name)}
            renderInput={params => (
              <TextField
                {...params}
                label="Search contract"
                margin="normal"
                variant="outlined"
                InputProps={{ ...params.InputProps, type: "search" }}
              />
            )}
          />{" "}
        </div>
      </div>
    );
  }
}

export default ContractsList;

im trying to get the selected value from the input field but its not working

Upvotes: 0

Views: 71

Answers (1)

Dekel
Dekel

Reputation: 62536

The onChange callback is being called once you change the value of the autocomplete (change of value is basically once you select/remove items from your list).

onChange={(ev, value) => {
  console.log(value);
}}

Here is a working example as part of the autocomplete:

<Autocomplete
  onChange={(ev, value) => {
    console.log(value);
  }}
  id="combo-box-demo"
  options={autoCompleteItems}
  getOptionLabel={(option) => option.title}
  style={{ width: 300 }}
  renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" />}
/>

You can see a codesandbox here.

Upvotes: 2

Related Questions